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
dockercommand. - 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:
docker exec -u 0 -it mycontainer bashRead 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:
docker logs <container-name>docker logs -f --tail 10 <container-name> # follow, starting from the last 10 linesdocker logs --since=2m <container-id> # output from the last 2 minutesdocker logs --since=1h <container-id> # output from the last hourCreate 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:
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:
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:
docker compose upAdd -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:
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/udpGRAYLOG_PASSWORD_SECRETsalts the stored passwords. Replace it with a long random string.GRAYLOG_ROOT_PASSWORD_SHA2is the SHA-256 hash of theadminuser’s password, here the hash ofadmin. Generate your own withecho -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:
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:
services: service1: profiles: - donotstartThe same mechanism starts optional services only when you ask for them. This service runs only with the dev profile:
services: dev_service: profiles: ["dev"]Activate the profile on the command line:
docker compose --profile dev upServices 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:
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: 10scondition: service_healthywaits until thehealthcheckofdbreports healthy. Here the check runspg_isreadyevery 10 seconds, up to 5 times, after a 30-second start period.restart: truerestartswebwhen Compose restartsdb, for example afterdocker compose restart db.condition: service_startedonly 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:
docker-machine create -d=virtualbox --virtualbox-cpu-count=2 --virtualbox-memory=4096 vbox-01docker-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:
docker-machine lsInitialize the swarm
Point your Docker client at the first machine, which will be the manager:
eval $(docker-machine env vbox-01)Then start swarm mode on it:
docker swarm initOn 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-addrSpecify the address that the other nodes can reach with --advertise-addr:
docker swarm init --advertise-addr=192.168.99.100The 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:
eval $(docker-machine env vbox-02)docker swarm join --token <worker-token> 192.168.99.100:2377Repeat the same steps for vbox-03:
eval $(docker-machine env vbox-03)docker swarm join --token <worker-token> 192.168.99.100:2377Port 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:
eval $(docker-machine env vbox-01)docker node lsThe 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:
docker service create --name=web --publish=9000:80 nginx:latestThe task can run on any of the three nodes. To see where it runs:
docker service ps webOpen the published port on each node to check that the service responds (open is the macOS command; use a browser or curl elsewhere):
open http://192.168.99.100:9000open http://192.168.99.101:9000open http://192.168.99.102:9000The 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.

Scale a service
Watch the tasks of the service. The REPLICAS count is 1/1 at this point:
watch -d docker service ps webScale the service from one replica to two:
docker service update --replicas=2 webTo see self-healing, list the containers on a node to get a container ID, then kill the container:
docker container lsdocker 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:
watch -d docker node lsYou can turn a worker into a manager or a manager back into a worker:
docker node promote vbox-02docker node demote vbox-02The 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:
docker service create \ --replicas 3 \ --name redis \ --update-delay 10s \ redis:3.0.6Inspect the service and its update policy:
docker service inspect --pretty redisUpdate the container image. The swarm manager applies the update to the tasks according to the UpdateConfig policy:
docker service update --image redis:3.0.7 redisWatch the rolling update with docker service ps:
docker service ps redisTo roll back to the previous specification:
docker service update --rollback redisDeploy 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:
docker stack deploy --compose-file docker-compose.yml stackdemoCheck that the services are running:
docker stack services stackdemoOnce 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:
docker stack rm stackdemoIf you started a local registry service to distribute the stack’s images, as the Docker stack tutorial does, remove it too:
docker service rm registryIf you were only testing on a local machine, take the Docker Engine out of swarm mode:
docker swarm leave --forceReferences
- docker container logs reference
- Use service profiles (Docker Compose)
- Control startup and shutdown order in Compose
- Deploy a stack to a swarm
- Use swarm mode routing mesh
- Apply rolling updates to a service
- Administer and maintain a swarm of Docker Engines
- Docker example voting app (GitHub)
- Container orchestration with Docker Swarm mode (video, in Turkish)