The Docker Book

Common tasks with docker and docker-compose

How to create a container

$ docker create <image-name>

The command above will create a container based on the docker image whose name is provided and returns an id for the container is has created. It will not start the container.

How to start a container

$ docker start -a <container-id>
$ docker start --attach <container-id>

The command above will start up a container that has already been created by using the provided container id. It will run the default start-up command associated with the container to set it up (Two alternative versions of the command have been provided)

How to run a container

$ docker run <image-name>
$ docker run <image-name> <alternate-startup-command>
$ docker run --detach <image-name>

The first command above will create and start a container based on the docker image whose name is provided. It will run the default start-up command associated with the container to set it up (image will be pulled down from dockerhub automatically if it is not available locally)

The second command above will create and start a container based on the docker image whose name is provided. It will run the alternate startup command provided, however, instead of the default startup command associated with the container to set it up.

The first command above will create and start a container based on the docker image whose name is provided. It will run the default start-up command associated with the container to set it up; but it will run the container in the background and return control back to the shell in which it was run.

How to list all containers

$ docker ps
$ docker ps --all
$ docker ps -a

The first command lists all containers currently running

The second command lists all containers that have ever been run

The third command is an alternate form of the second command

How to delete all containers

$ docker container prune --force

The command above will delete all containers

How to get logs from a running container

$ docker logs <container-id>

The command above will print logs for the container whose id is provided

How to terminate a container

$ docker stop <container-id>
$ docker kill <container-id>

The first command requests the container whose id was passed to shut down. It waits 10 seconds and if the container has not shut down it kills it.

The second command kills the container whose id was provided without waiting 10 seconds right away.

How to run multiple container commands

$ docker exec -it <container-id> <comand>

The command above attaches an interactive teletype to the running container whose id was provided and runs the provided command inside of the container.

A user can run the above multiple times, using a different command to run in the container each time.

How to get shell access to a container

$ docker exec --interactive --tty <container-id> sh
$ docker run --interactive --tty <image-name> sh

The first command provides interactive shell access to a container that is running.

The second command creates and starts a container based on the provided image id. It runs the shell command instead of running the startup command associated with the container.

How to build a custom image from a Dockerfile

# Define base image
FROM alpine

# Define dependencies
RUN apk add --update redis

# Define start-up command
CMD ["redis-server"]

Dockerfile defines a docker file. The instructions inside it define how to build a custom redis image. The file must be called Dockerfile and can only contain Docker commands and comments.

Build image defines what is run from the folder in which the Dockerfile resides. It executes the instructions inside the Dockerfile to create an image with the name debugme/redis:latest and the dot is used to specify which directory the resources to include in the building of the image can be found in. The build command allows you to specify an alternate name for the Docker file with the --file flag.

Run image shows two equivalent ways to run this custom image. If latest is omitted, then it is assumed to be present by default.

How to build a tagged image from a container

// (1) startup a container from an alpine image
$ docker run -it alpine sh

// (2) install redis on the container
% apk add --update redis

// (3) in a new shell, create image from modified container 
// with default start-up command 
docker commit -c 'CMD ["redis-server"]' 06bbfbcbc3bf debugme/redis:home

// (4) Start up the image you just created
docker run debugme/redis:home

How to run a custom server in a docker container

# Dependencies least likely to change
FROM node:alpine
WORKDIR /home/mywebapp
EXPOSE 8080
CMD ["npm", "start"]
COPY ./package.json ./
RUN npm install

# Dependencies most likely to change
COPY ./ ./

Dockerfile: instructions on how to create a custom image

Build image: the command at the terminal to build the image

Run image: terminal command to run image as a container

package.json: dependencies and scripts to build and run server

index.js: a JS code implementation for a simple server

How to delete all Docker images that have been downloaded

$ docker image prune --all --force

Docker-compose commands

$ docker-compose build        // builds docker container(s)
$ docker-compose up           // starts up docker container(s) in foreground
$ docker-compose up -d        // starts up docker container(s) in background
$ docker-compose down         // brings docker containers down
$ docker-compose ps           // get the status of the running containers

How to run an application composed of multiple docker containers

const express = require("express");
const redis = require("redis");

const rootPath = "/";

const {
  env: { nodePort, redisHost, redisPort }
} = process;

const rootHandler = client => (_, response) => {
  client.get("visits", (error, visits) => {
    if (error) {
      response.send(error);
    } else {
      response.send(`visits: ${visits}`);
      client.set("visits", parseInt(visits, 10) + 1);
    }
  });
};

const callback = port => () =>
  console.log(`Listening on http://localhost:${port}`);

const client = redis.createClient({ host: redisHost, port: redisPort });
client.set("visits", 0);

const server = express();
server.get(rootPath, rootHandler(client));
server.listen(nodePort, callback(nodePort));

How to specify a restart policy for your docker container

const express = require("express");
const redis = require("redis");

const rootPath = "/";

const {
  env: { nodePort, redisHost, redisPort }
} = process;

const rootHandler = client => (_, response) => {
  // process.exit(0)
  process.exit(1)
  client.get("visits", (error, visits) => {
    if (error) {
      response.send(error);
    } else {
      response.send(`visits: ${visits}`);
      client.set("visits", parseInt(visits, 10) + 1);
    }
  });
};

const callback = port => () =>
  console.log(`Listening on http://localhost:${port}`);

const client = redis.createClient({ host: redisHost, port: redisPort });
client.set("visits", 0);

const server = express();
server.get(rootPath, rootHandler(client));
server.listen(nodePort, callback(nodePort));

How to sync local frontend changes with Docker

from node:alpine
workdir /app
cmd [ "npm", "run", "start" ]
copy package.json .
run npm install
copy . .

How to sync local frontend changes with Docker Compose

from node:alpine
workdir /usr/app
cmd ["npm", "start"]
copy package.json .
run npm install
copy . .

How to sync local backend changes with Docker Compose

FROM node:alpine
WORKDIR /usr/app
CMD ["npm", "start"]
COPY package.json .
RUN npm install
COPY . .

How to create a container using a multi-step approach

version: "3"
services: 
  app:
    stdin_open: true
    ports:
      - 3000:3000
    volumes:
      - .:/usr/app
      - /usr/app/node_modules
    build:
      context: .
      dockerfile: Dockerfile.dev

How to deploy code changes to GitHub and test pull requests on TravisCI

version: "3"
services: 
  app:
    ports:
      - 3000:3000
    volumes:
      - .:/usr/docker-react
      - /usr/docker-react/node_modules
    build:
      context: .
      dockerfile: Dockerfile.dev

How to get container id via image name

// In the example below we find the container by looking for "35mm" 
// which is part of the image name and then opening a shell on it

$ docker exec -it `docker ps | grep 35mm | awk '{ print $1}'` sh

Last updated