Skip to content

Instantly share code, notes, and snippets.

@Rafisto
Created February 12, 2024 20:39
Show Gist options
  • Save Rafisto/b2e98ddde1f7419f400c06018e0e4688 to your computer and use it in GitHub Desktop.
Save Rafisto/b2e98ddde1f7419f400c06018e0e4688 to your computer and use it in GitHub Desktop.
ENVs for `docker` and `docker compose`

On the fly ENVs for Docker containers.

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.

  1. Dockerfile:
FROM ubuntu:latest

ENV POSTGRES_USER=default_user
ENV POSTGRES_PASSWORD=default_password

COPY innerscript.sh /innerscript.sh

CMD ["/bin/bash", "/innerscript.sh"]
  1. innerscript.sh:
echo "postgres user = ${POSTGRES_USER}"
echo "postgres password = ${POSTGRES_PASSWORD}"
  1. outerscript.sh:
docker build -t example-sh .
docker run --env POSTGRES_USER=postgres --env POSTGRES_PASSWORD=passwd example-sh
  1. Container logs:
$ docker logs <tag>
postgres user = postgres
postgres password = passwd

envsubst application for docker compose.

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.

  1. 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
  1. Provide your environment with desired variables
$ export POSTGRES_USER=pguser
$ export POSTGRES_PASSWORD=1234
  1. Substitute variables inside the file for the environment variables.
$ echo "$(envsubst < compose.yaml)"
  1. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment