Skip to content

Docker

Docker reference: container shells and logs, networks, Docker Compose examples, profiles and startup order, and Swarm mode clusters.

10 min readUpdated

Docker packages an application and its dependencies into an image and runs it as an isolated container. This note covers everyday container commands (shells, logs, networks), Docker Compose files for multi-container setups, and Swarm mode for running services across a cluster of Docker hosts.

Docker platform components

The Docker platform has included these products over the years:

  • Docker Engine and Docker CLI: the daemon and the docker command.
  • Docker Compose (formerly “Fig”): multi-container applications defined in a YAML file.
  • Docker Swarm mode: clustering built into Docker Engine.
  • Docker Machine, Kitematic, Docker Cloud (formerly “Tutum”) and Docker Datacenter: these are discontinued or no longer Docker products. Docker Machine is still used in the Swarm walkthrough below, which predates its retirement.

Open a shell as root in a container

docker exec runs a command in a running container. With -u 0 it runs as the root user (user ID 0) instead of the image’s default user, which helps when you need to install a package or inspect files the default user cannot read:

Terminal window
docker exec -u 0 -it mycontainer bash

Read container logs

docker logs prints what the container wrote to standard output and standard error. -f follows new output, --tail limits the output to the last lines, and --since accepts a relative time such as 2m or 1h:

Terminal window
docker logs <container-name>
docker logs -f --tail 10 <container-name> # follow, starting from the last 10 lines
docker logs --since=2m <container-id> # output from the last 2 minutes
docker logs --since=1h <container-id> # output from the last hour

Create and connect to a network

Containers on the same user-defined network can reach each other by container name. Create a network, attach a running container to it and inspect the result:

Terminal window
docker network create <network-name>
docker network inspect <network-name>
docker network connect <network-name> <container-name>
docker network inspect <network-name>

To start a container directly on a network, pass --network to docker run. This example also publishes container port 8080 on host port 8282:

Terminal window
docker run --network <network-name> -d -p 8282:8080 --name <container-name> aripd/app-name

--net is an older alias of --network.

Docker Compose

Docker Compose starts several containers from one file. Create a docker-compose.yml (or compose.yaml) file in the project directory and run:

Terminal window
docker compose up

Add -d to run the containers in the background. Older installations use the standalone docker-compose command with the same arguments. The top-level version: key that older Compose files start with is obsolete; current Compose ignores it, so the examples below leave it out.

Example: Graylog

This file runs Graylog with MongoDB and Elasticsearch. The web interface and REST API listen on port 9000, and the other ports accept Syslog and GELF log messages:

docker-compose.yml
services:
# MongoDB: https://hub.docker.com/_/mongo/
mongodb:
image: mongo:3
# Elasticsearch: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/docker.html
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:5.6.2
environment:
- http.host=0.0.0.0
- transport.host=localhost
- network.host=0.0.0.0
# Disable X-Pack security: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/security-settings.html#general-security-settings
- xpack.security.enabled=false
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ulimits:
memlock:
soft: -1
hard: -1
mem_limit: 1g
# Graylog: https://hub.docker.com/r/graylog/graylog/
graylog:
image: graylog/graylog:2.4.3-1
environment:
# CHANGE ME!
- GRAYLOG_PASSWORD_SECRET=somepasswordpepper
# Password: admin
- GRAYLOG_ROOT_PASSWORD_SHA2=8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
- GRAYLOG_WEB_ENDPOINT_URI=http://127.0.0.1:9000/api
links:
- mongodb:mongo
- elasticsearch
depends_on:
- mongodb
- elasticsearch
ports:
# Graylog web interface and REST API
- 9000:9000
# Syslog TCP
- 514:514
# Syslog UDP
- 514:514/udp
# GELF TCP
- 12201:12201
# GELF UDP
- 12201:12201/udp
  • GRAYLOG_PASSWORD_SECRET salts the stored passwords. Replace it with a long random string.
  • GRAYLOG_ROOT_PASSWORD_SHA2 is the SHA-256 hash of the admin user’s password, here the hash of admin. Generate your own with echo -n 'yourpassword' | sha256sum.

Note: this example uses Graylog 2.4 with Elasticsearch 5.6 and MongoDB 3. Current Graylog releases need newer images and different settings; follow the Graylog documentation for those.

Example: MySQL with phpMyAdmin

This file runs MySQL with phpMyAdmin on port 8081. The database files are stored in ./data/db on the host, and any .sql or .sh files in ./conf/init-scripts/mysql run when the database is created for the first time:

docker-compose.yml
services:
mysql-server:
image: mysql:8.0.23
volumes:
- ./data/db:/var/lib/mysql
- ./conf/init-scripts/mysql:/docker-entrypoint-initdb.d
restart: always
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: dbname
MYSQL_USER: username
MYSQL_PASSWORD: secret
ports:
- "3306:3306"
command: ['--character-set-server=utf8mb4', '--collation-server=utf8mb4_bin']
phpmyadmin:
image: phpmyadmin/phpmyadmin:5.1.0
restart: always
environment:
PMA_HOST: mysql-server
PMA_USER: root
PMA_PASSWORD: secret
ports:
- "8081:80"

PMA_HOST is the Compose service name of the database, which works as a host name on the Compose network. The command arguments set the server’s default character set and collation.

Disable a service with profiles

A service that lists one or more profiles starts only when one of its profiles is active. To keep a service from starting, give it a profile you never activate:

docker-compose.yml
services:
service1:
profiles:
- donotstart

The same mechanism starts optional services only when you ask for them. This service runs only with the dev profile:

docker-compose.yml
services:
dev_service:
profiles: ["dev"]

Activate the profile on the command line:

Terminal window
docker compose --profile dev up

Services without a profiles key always start.

Control startup and shutdown order

depends_on controls the order in which services start and stop. With the long syntax, a dependency can also wait for a condition. In this example web starts only after db passes its health check and redis has started:

docker-compose.yml
services:
web:
build: .
depends_on:
db:
condition: service_healthy
restart: true
redis:
condition: service_started
redis:
image: redis
db:
image: postgres
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
retries: 5
start_period: 30s
timeout: 10s
  • condition: service_healthy waits until the healthcheck of db reports healthy. Here the check runs pg_isready every 10 seconds, up to 5 times, after a 30-second start period.
  • restart: true restarts web when Compose restarts db, for example after docker compose restart db.
  • condition: service_started only waits for the container to start, not for the service inside it to be ready.

Docker Swarm mode

Swarm mode turns several Docker hosts into one cluster. Manager nodes keep the cluster state and schedule services; worker nodes run the containers. The steps below build a three-node cluster on local virtual machines and deploy services to it.

Create machines

For a development cluster, first create virtual machines. This walkthrough uses docker-machine, which is now deprecated and archived; you can create the machines with another tool, such as Vagrant, or use cloud instances instead. Docker Machine itself could also create machines with the amazonec2, azure, digitalocean and google drivers instead of virtualbox.

To create three VirtualBox machines with 2 CPUs and 4 GB of RAM each, run:

Terminal window
docker-machine create -d=virtualbox --virtualbox-cpu-count=2 --virtualbox-memory=4096 vbox-01
docker-machine create -d=virtualbox --virtualbox-cpu-count=2 --virtualbox-memory=4096 vbox-02 &
docker-machine create -d=virtualbox --virtualbox-cpu-count=2 --virtualbox-memory=4096 vbox-03 &

The & at the end sends a command to the background, so the second and third machines are created in parallel. --virtualbox-memory is in megabytes.

To list the machines:

Terminal window
docker-machine ls

Initialize the swarm

Point your Docker client at the first machine, which will be the manager:

Terminal window
eval $(docker-machine env vbox-01)

Then start swarm mode on it:

Terminal window
docker swarm init

On a VirtualBox machine, this fails with an error like the following, because the machine has two network interfaces:

Error response from daemon: could not choose an IP address to advertise since this system has multiple addresses on different interfaces (10.0.2.15 on eth0 and 192.168.99.100 on eth1) - specify one with --advertise-addr

Specify the address that the other nodes can reach with --advertise-addr:

Terminal window
docker swarm init --advertise-addr=192.168.99.100

The output confirms that the node is now a manager and prints the command for adding workers:

Swarm initialized: current node (chfpci27hkjr58m4wbfhe72wz) is now a manager.

To print the join command again later, run docker swarm join-token worker for a worker or docker swarm join-token manager for a manager.

Join worker nodes

Point the client at the second machine and join it to the swarm as a worker, using the token from the init output:

Terminal window
eval $(docker-machine env vbox-02)
docker swarm join --token <worker-token> 192.168.99.100:2377

Repeat the same steps for vbox-03:

Terminal window
eval $(docker-machine env vbox-03)
docker swarm join --token <worker-token> 192.168.99.100:2377

Port 2377 is the swarm management port on the manager. Node commands work only on a manager, so switch back to vbox-01 to list the nodes:

Terminal window
eval $(docker-machine env vbox-01)
docker node ls

The manager and worker nodes are now ready to run services.

Create a service

Create a service named web that runs nginx and publishes container port 80 on port 9000 of the swarm:

Terminal window
docker service create --name=web --publish=9000:80 nginx:latest

The task can run on any of the three nodes. To see where it runs:

Terminal window
docker service ps web

Open the published port on each node to check that the service responds (open is the macOS command; use a browser or curl elsewhere):

Terminal window
open http://192.168.99.100:9000
open http://192.168.99.101:9000
open http://192.168.99.102:9000

The service has a single task on one of the three nodes, yet it answers on all three. This is the work of the routing mesh: every node in the swarm accepts connections on the published ports of every service, even if no task of that service runs on the node, and routes each request to an active container.

The diagram below shows a service with two tasks on node1 and node2. The swarm load balancer on each node, node3 included, forwards requests on the published port to one of the tasks over the ingress network.

Swarm ingress routing mesh: the load balancer on each of three nodes forwards the published port to service tasks on node1 and node2

Scale a service

Watch the tasks of the service. The REPLICAS count is 1/1 at this point:

Terminal window
watch -d docker service ps web

Scale the service from one replica to two:

Terminal window
docker service update --replicas=2 web

To see self-healing, list the containers on a node to get a container ID, then kill the container:

Terminal window
docker container ls
docker container kill <container-id>

The swarm scheduler notices the missing task and starts a new container, so the service returns to the desired number of running replicas.

Promote and demote nodes

Watch the node list in one terminal:

Terminal window
watch -d docker node ls

You can turn a worker into a manager or a manager back into a worker:

Terminal window
docker node promote vbox-02
docker node demote vbox-02

The MANAGER STATUS column shows Leader or Reachable for managers. A swarm can have several managers, but only one is the leader; the others are reachable.

The number of managers is a trade-off between performance and fault tolerance. More managers make the swarm more fault-tolerant, but they reduce write performance, because more nodes must acknowledge each update to the swarm state, which means more network round trips.

Managers use the Raft consensus algorithm to manage the swarm state. Raft requires a majority of managers, called the quorum, to agree on proposed updates such as adding or removing nodes.

You can scale a swarm down to a single manager, but you cannot demote the last manager. A single manager is not recommended, because the swarm cannot survive its loss. Use an odd number of managers: adding one more to make an even number does not make the quorum easier to keep.

Apply rolling updates and roll back a service

Deploy an older version of Redis with three replicas. --update-delay sets the wait time between updating one task and the next:

Terminal window
docker service create \
--replicas 3 \
--name redis \
--update-delay 10s \
redis:3.0.6

Inspect the service and its update policy:

Terminal window
docker service inspect --pretty redis

Update the container image. The swarm manager applies the update to the tasks according to the UpdateConfig policy:

Terminal window
docker service update --image redis:3.0.7 redis

Watch the rolling update with docker service ps:

Terminal window
docker service ps redis

To roll back to the previous specification:

Terminal window
docker service update --rollback redis

Deploy a stack from a Compose file

In swarm mode, docker stack deploy deploys a complete application stack described in a Compose file (format version 3.0 or later). The example voting app is a good multi-service stack to try.

Create the stack. The last argument is the stack name; every network, volume and service of the stack is prefixed with it:

Terminal window
docker stack deploy --compose-file docker-compose.yml stackdemo

Check that the services are running:

Terminal window
docker stack services stackdemo

Once the stack is running, the REPLICAS column shows 1/1 for each service. This can take some time on a multi-node swarm, because every node has to pull the images.

Remove the stack:

Terminal window
docker stack rm stackdemo

If you started a local registry service to distribute the stack’s images, as the Docker stack tutorial does, remove it too:

Terminal window
docker service rm registry

If you were only testing on a local machine, take the Docker Engine out of swarm mode:

Terminal window
docker swarm leave --force

References

Related notes

4 min readTürkçe

Ollama

GPU'suz, yalnız CPU ile çalışan makinelerde Ollama ile yerel LLM çalıştırma ve hızı belirleyen ayarlar.

  • AI & Data
  • DevOps & Containers
7 min readTürkçe

Podman

Podman kurulumu, rootless container'ları systemd ve Quadlet ile kullanıcı servisi olarak çalıştırma ve sık görülen hatalar.

  • DevOps & Containers
4 min read

Kubernetes

Run containers and local Kubernetes on macOS with Podman, Podman Desktop, kubectl and minikube, and describe workloads in Kubernetes YAML.

  • DevOps & Containers

Type to search the whole site.