Docker

Docker Compose: your services in one file

With Docker Compose you put everything a program needs in one file: the image, ports, volumes and settings. Starting, stopping and updating is done with one command, and you can save the file as a backup of your settings. Compose is included with the Docker installation; you use it with docker compose (without a hyphen).

A first compose.yaml

Create a folder, for example ~/web, and put the file compose.yaml in it:

services:
  web:
    image: nginx:alpine
    ports:
      - "8080:80"
    volumes:
      - ./site:/usr/share/nginx/html:ro
    restart: unless-stopped

Put a file index.html in the site folder and start it:

docker compose up -d

Open http://your-server:8080. Note the indentation of two spaces in the file: that’s important in YAML. Made a mistake? Check the file with our YAML tool or with docker compose config.

The most important commands

Run them in the folder with the file:

docker compose up -d        # start everything (and create)
docker compose ps           # what's running
docker compose logs -f      # follow the log
docker compose restart      # restart
docker compose pull         # fetch newer images
docker compose down         # stop and remove the containers

With docker compose down your volumes and folders remain intact. If you add -v, the named volumes are also removed and your data is gone. So only do that if you really want to.

Updating in two commands

docker compose pull
docker compose up -d

Compose fetches the new image and only replaces the containers that have changed. Your data in volumes is preserved.

An app with a database

This example starts a database and the administration program Adminer. The two find each other by the name db. You don’t put the passwords in the file, but in a separate file .env in the same folder:

services:
  db:
    image: mariadb:11
    environment:
      MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
      MARIADB_DATABASE: app
      MARIADB_USER: app
      MARIADB_PASSWORD: ${DB_PASSWORD}
    volumes:
      - db-data:/var/lib/mysql
    restart: unless-stopped

  adminer:
    image: adminer
    ports:
      - "8081:8080"
    depends_on:
      - db
    restart: unless-stopped

volumes:
  db-data:
# .env
DB_ROOT_PASSWORD=use-a-long-password-here
DB_PASSWORD=and-a-different-password-here

Create strong passwords with our password generator. Then restrict who may read the file with chmod 600 .env (see the chmod calculator) and never put .env on GitHub.

Useful habits

  • One folder per program, containing compose.yaml and any data. This way you can easily move a program or make a backup.
  • Put a version after the image (like mariadb:11) instead of latest, so that an update doesn’t make an unexpected big jump.
  • View ready-made examples in Useful Docker programs for home.
Can't do it yourself? Have an expert come to your home via hulpaanhuis.nl