Understanding What I Write in a Dockerfile and compose.yml

Contents

Introduction

I have been copying the Dockerfile and compose.yml from existing projects and running them. They work, so it has not been a problem, but I could not explain what each line is for.

This time I set up one small example and checked, from top to bottom, what goes in which file, and for things that can be written in both, which one takes effect.

The example is two containers, PHP and PostgreSQL

It just starts one PHP built-in server and one PostgreSQL.

Dockerfile
FROM php:8.4-cli

RUN apt-get update \
 && apt-get install -y --no-install-recommends libpq-dev \
 && docker-php-ext-install pdo_pgsql \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /work

ENV APP_ENV=local
ENV ONLY_IN_DOCKERFILE=yes

EXPOSE 8080

CMD ["php", "-S", "0.0.0.0:8080", "-t", "public"]
compose.yml
services:
  php:
    build:
      context: .
    working_dir: /work
    volumes:
      - .:/work
    ports:
      - "8080:8080"
    environment:
      APP_ENV: docker
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: handson
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d handson"]
      interval: 2s
      timeout: 3s
      retries: 30

volumes:
  pgdata:

The page it serves only prints an environment variable and the DB version.

public/index.php
<?php
header('Content-Type: text/plain; charset=utf-8');

echo 'APP_ENV=', getenv('APP_ENV'), PHP_EOL;

$pdo = new PDO('pgsql:host=db;dbname=handson', 'postgres', 'postgres');
echo $pdo->query('select version()')->fetchColumn(), PHP_EOL;

First, I check that it works. This is the result after docker compose up -d --build.

$ curl -s http://localhost:8080/
APP_ENV=docker
PostgreSQL 16.15 (Debian 16.15-1.pgdg13+2) on aarch64-unknown-linux-gnu, compiled by gcc (Debian 14.2.0-19) 14.2.0, 64-bit

The dividing line is build time vs. start time

Both look like container settings, so I thought both were re-read every time the container starts. The Dockerfile is read at build time, and compose.yml is read every time you start.

Dockerfile compose.yml
When it is read At build time Every docker compose up
Result Stays in the image Does not stay
What it decides What is inside the image How it is started

To begin with, what a Dockerfile builds is an image, not a container. build: is an instruction to "build an image from the Dockerfile in this directory", and this is where compose.yml and the Dockerfile meet.

compose.yml
  services:
    php:
      build:
        context: .        ──▶ ./Dockerfile ──▶ image ──▶ php container

    db:
      image: postgres:16  ─────────────────▶ image ──▶ db container

There are two ways to get to an image. build: builds it yourself from a Dockerfile, and image: pulls a ready-made one. Either way, what comes after is a container. The example has two containers because there are two names under services, and only php goes through the Dockerfile.

So when does that build run? docker compose up builds only when there is no image. With --build, it goes to rebuild even if there is one.

$ docker compose up -d          # image exists, no --build
 Network dockerfile-compose-lab_default Creating 
 Network dockerfile-compose-lab_default Created 
 Container dockerfile-compose-lab-db-1 Creating 
 Container dockerfile-compose-lab-db-1 Created 

$ docker compose up -d --build  # Dockerfile not changed
 Image dockerfile-compose-lab-php Building 
#6 [2/3] RUN apt-get update  && apt-get install -y --no-install-recommends libpq-dev  && docker-php-ext-install pdo_pgsql  && rm -rf /var/lib/apt/lists/*
#6 CACHED
#7 [3/3] WORKDIR /work
#7 CACHED

The first one shows only Creating and never enters a build. The second one has --build, so it enters a build every time, but the Dockerfile has not changed, so everything is CACHED and apt-get does not run. It only re-runs the steps from scratch when you rewrite a line of the Dockerfile, from that line down.

$ docker compose ps --format 'table {{.Service}}	{{.Image}}	{{.State}}'
SERVICE   IMAGE                        STATE
db        postgres:16                  running
php       dockerfile-compose-lab-php   running

--format is an option that picks which columns to show. The IMAGE column shows which image that container was started from. The image itself does not run. It is the stored result of either building with build or pulling, and what you get by starting it is a container.

With this line drawn, I read the files again from the top.

What you write in the Dockerfile is baked into the image

These are the six that appear in the example's Dockerfile.

Key What it does
FROM Decides the base image
RUN Runs only at build time, and the result stays in the image
WORKDIR Creates the directory if missing and moves into it. It becomes the base for the following lines and CMD
ENV Bakes an environment variable into the image
EXPOSE Records in the image which port it listens on. It does not publish it
CMD Baked into the image, but runs every time the container starts

I thought the base image included a web server, but it does not, so I start one myself with CMD.

CMD ["php", "-S", "0.0.0.0:8080", "-t", "public"]

It uses 0.0.0.0 because with 127.0.0.1 it can only be reached from inside the container.

I wrongly thought that writing EXPOSE would make it visible from the browser on port 8080. All it actually does is record in the image that "this image listens on port 8080". What makes it reachable from the host is ports in compose.yml. I will quote what the official docs say about this later.

ENV APP_ENV has the same key in compose.yml's environment too, while ONLY_IN_DOCKERFILE exists only here. I put it on only one side on purpose.

(Note) Why RUN is chained into one line with &&

Each RUN is one layer. If you split update and install, install runs against the old package list, and if you split out rm -rf, the layer from before the deletion remains.

What you write in compose.yml takes effect on every run

On the compose.yml side, these are the eight that appear in the example.

Key What it does Dockerfile counterpart
services Lists the containers. Each name becomes the host name as is None
build Builds the Dockerfile in the context: directory None
image Pulls a ready-made image without building None
working_dir The container's working directory WORKDIR
volumes Overlays a host or Docker storage area onto the container None
ports Makes a container port reachable from the host EXPOSE
environment Passes environment variables ENV
depends_on / healthcheck Start order, and waiting on a condition None

index.php can connect with pgsql:host=db because compose puts the containers on the same network and resolves names by service name.

    ports:
      - "8080:8080"

The 8080 on the left is the host side, and the right is the container side. The number is the same as EXPOSE 8080, but this is what makes it reachable from the host.

The Dockerfile says APP_ENV=local, yet the first curl returned docker, the value written in environment.

How long volumes last depends on how you write them.

    volumes:
      - .:/work
    volumes:
      - pgdata:/var/lib/postgresql/data
Syntax What it is After down -v
.:/work (bind mount) A directory on the host Not deleted
pgdata (named volume) A storage area managed by Docker Deleted

There is no COPY in the Dockerfile, so public/index.php gets into the container thanks to .:/work. If you save on the host side, a reload picks it up as is.

https://docs.docker.com/engine/storage/volumes/

With only depends_on: [db], php starts running as soon as db has started. Postgres takes a few seconds before it accepts connections, and when I sent a request during that time it failed with Connection refused. Adding condition: service_healthy makes it wait until the healthcheck on the db side (pg_isready every 2 seconds, up to 30 times) passes.

Caution

Writing healthcheck on the php side has no effect. condition looks at the service being waited on, so if db does not have one, you cannot use this condition.

https://docs.docker.com/reference/compose-file/services/#depends_on

Having read through from the top, several of the same names I saw in the Dockerfile came up again.

For things you can write in both, compose wins

Among the shared names that came up, the one with the same value too was /work. That is WORKDIR in the Dockerfile and working_dir in compose.yml. Because they were the same, I had glossed over it, but if it can be written in two places, which one takes effect must be defined. I put a different value on the compose side.

Dockerfile compose.yml Which one takes effect
WORKDIR working_dir: compose
ENV environment: compose (only the same keys are overridden, the rest remain)
CMD command: compose
ENTRYPOINT entrypoint: compose (CMD is dropped in this case)
EXPOSE ports: Different roles. EXPOSE does not publish

The Compose file reference says that both working_dir and command "override" the image's value. These two are by spec. ENV is the one case that is different.

WORKDIR and ENV took the compose values

Only the side given working_dir: /from-compose and APP_ENV: docker changed.

--- no override ---
APP_ENV=local WD=/work
--- with override ---
APP_ENV=docker WD=/from-compose

The image side has not been rewritten. From here I go back to the example's php, and these are the results of asking the image, and the container started from it, for the same variable.

$ docker image inspect dockerfile-compose-lab-php --format '{{range .Config.Env}}{{println .}}{{end}}' | grep APP_ENV
APP_ENV=local

$ docker inspect $(docker compose ps -q php) --format '{{range .Config.Env}}{{println .}}{{end}}' | grep APP_ENV
APP_ENV=docker

What compose does is not rewrite the image, but pass a different value at the moment it starts the container. The Dockerfile's APP_ENV=local stays baked into the image.

environment: did not wipe out all of ENV

The Dockerfile also has ONLY_IN_DOCKERFILE=yes. I override only APP_ENV and run env (output order is not fixed).

$ docker compose -f compose.override-demo.yml run --rm override env | grep -E "APP_ENV|ONLY_IN_DOCKERFILE"
ONLY_IN_DOCKERFILE=yes
APP_ENV=docker

I thought it would be replaced wholesale, but only the same key was overridden, and the rest remained. However, the environment section of the Compose file reference does not describe how it relates to the image's ENV. I cannot say for sure that it is the spec, so I am writing it down as behavior I confirmed on my machine.

ENV does not show up in docker compose config

$ docker compose -f compose.override-demo.yml config override
name: verify
services:
  override:
    build:
      context: /path/to/dockerfile-compose-lab
      dockerfile: Dockerfile
    command:
      - php
      - -r
      - echo 'APP_ENV=', getenv('APP_ENV'), ' WD=', getcwd(), PHP_EOL;
    environment:
      APP_ENV: docker
    networks:
      default: null
    working_dir: /from-compose
networks:
  default:
    name: verify_default

ONLY_IN_DOCKERFILE does not show up. I have concluded before that a variable not shown here was not set, but it was actually inside the container. My understanding is that config only looks at compose.yml and does not follow what is inside the image. The final values can only be seen with docker inspect or with env inside the container.

EXPOSE does not publish a port

This is a separate test file from the example. command: is the same, and the only difference is ports:.

$ docker compose -f compose.expose-demo.yml ps --format 'table {{.Service}}	{{.State}}	{{.Ports}}'
SERVICE       STATE     PORTS
only-expose   running   8080/tcp
with-ports    running   0.0.0.0:18080->8080/tcp, [::]:18080->8080/tcp
--- viewed with inspect ---
only-expose: ExposedPorts={"8080/tcp":{}} PortBindings={}
with-ports: ExposedPorts={"8080/tcp":{}} PortBindings={"8080/tcp":[{"HostIp":"","HostPort":"18080"}]}

ExposedPorts is the same for both, and the difference is PortBindings. What publishes the port is ports:. The Dockerfile reference says so too.

The EXPOSE instruction doesn't actually publish the port.

Then can a service without ports: not be reached at all? I called it from the same network (this test file has no environment:, so it stays local).

$ docker compose -f compose.expose-demo.yml exec -T with-ports php -r "echo file_get_contents('http://only-expose:8080/');"
APP_ENV=local

It is just not exposed to the host. Inside the compose network you can reach it by name. Even though the example's db has no ports:, php can connect to it.

(Note) Writing entrypoint drops CMD

This is a different image that has an ENTRYPOINT.

FROM alpine:3.20
ENTRYPOINT ["echo", "EP:"]
CMD ["cmd-from-dockerfile"]
--- as is ---
EP: cmd-from-dockerfile
--- override command only ---
EP: cmd-from-compose
--- override entrypoint only ---
EP-from-compose:

With only command:, ENTRYPOINT remains, and with entrypoint:, CMD is dropped along with it. The official docs state this explicitly too.

If entrypoint is non-null, Compose ignores any default command from the image, for example the CMD instruction in the Dockerfile.

https://docs.docker.com/reference/compose-file/services/#entrypoint

Closing

I can now explain, line by line, the files I had been copying and running. I was able to draw the line that for things you can write in both, compose wins. I would be glad if this helps anyone else who has been copying and running these files the same way.

References

Translated from the Japanese original.

Thanks. I'll look into it.

Spotted a mistake?

Tell me what's wrong and I'll fix it. Only I see what you send.