Reputation: 11920
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"
?
Is there a way to pass the variable into the docker-compose.yml
file dynamically?
Additionally, can I specify a default value (e.g. development
) in docker-compose.yml
in case I don't pass in anything?
Thanks!
Upvotes: 4
Views: 4010
Reputation: 2184
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
Upvotes: 5