Define environment variables, which are then used within the container during runtime.
The innerscript.sh
script echoes the values of these variables.
When running the container, environment variables can be overridden using the --env
flag.
Dockerfile
:
FROM ubuntu:latest
ENV POSTGRES_USER=default_user
ENV POSTGRES_PASSWORD=default_password
COPY innerscript.sh /innerscript.sh
CMD ["/bin/bash", "/innerscript.sh"]
innerscript.sh
:
echo "postgres user = ${POSTGRES_USER}"
echo "postgres password = ${POSTGRES_PASSWORD}"
outerscript.sh
:
docker build -t example-sh .
docker run --env POSTGRES_USER=postgres --env POSTGRES_PASSWORD=passwd example-sh
- Container logs:
$ docker logs <tag>
postgres user = postgres
postgres password = passwd
In this example, envsubst is used to substitute environment variables defined in the shell into a Docker Compose file. This allows for dynamic configuration of services within the Docker Compose file based on the environment variables provided.
- This is an example
compose.yaml
.
version: '3.1'
services:
db:
image: postgres
restart: always
environment:
POSTGRES_USER: "${POSTGRES_USER}"
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD}"
adminer:
image: adminer
restart: always
ports:
- 8080:8080
- Provide your environment with desired variables
$ export POSTGRES_USER=pguser
$ export POSTGRES_PASSWORD=1234
- Substitute variables inside the file for the environment variables.
$ echo "$(envsubst < compose.yaml)"
- Output:
version: '3.1'
services:
db:
image: postgres
restart: always
environment:
POSTGRES_USER: "pguser"
POSTGRES_PASSWORD: "1234"
adminer:
image: adminer
restart: always
ports:
- 8080:8080