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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With