Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically passing in an argument into `docker-compose.yml`

I can specify an arg in docker-compose.yml as follows (e.g. RAILS_ENV)

version: '3'
services:
  web:
    build:
     context: .
     args:
       RAILS_ENV: production

The Dockerfile uses this ARG and sets anENV so that my image gets built with that environment variable:

FROM ruby:2.5.1

# ...

ARG RAILS_ENV
ENV RAILS_ENV=$RAILS_ENV

# ...
# Image contains environment variable `$RAILS_ENV` as `"production"`

However, what if I want to use something other than the hard-coded value of "production" ?

  1. Is there a way to pass the variable into the docker-compose.yml file dynamically?

  2. Additionally, can I specify a default value (e.g. development) in docker-compose.yml in case I don't pass in anything?

Thanks!

like image 716
user2490003 Avatar asked Oct 16 '25 06:10

user2490003


1 Answers

Yes, you can do this.

First, you will need to create .env with variables (in this same location as your Dockerfile):

RAILS_ENV=production

You are not committing this file to the repository (You should add it to .gitignore). And then you can start to use them in Dockerfile:

version: '3'
services:
  web:
    build:
     context: .
     args:
       RAILS_ENV: ${RAILS_ENV}

There are two ways to define default values for variables:

${VARIABLE:-default} evaluates to default if VARIABLE is unset or empty in the environment. ${VARIABLE-default} evaluates to default only if VARIABLE is unset in the environment.

So for example:

version: '3'
services:
  web:
    build:
     context: .
     args:
       RAILS_ENV: ${RAILS_ENV:-development}

Read more here: https://docs.docker.com/compose/compose-file/#variable-substitution

like image 56
Marek Skiba Avatar answered Oct 18 '25 22:10

Marek Skiba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!