DockerManaging containers

Syntax

  • docker rm [OPTIONS] CONTAINER [CONTAINER...]
  • docker attach [OPTIONS] CONTAINER
  • docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
  • docker ps [OPTIONS]
  • docker logs [OPTIONS] CONTAINER
  • docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...]

Remarks

  • In the examples above, whenever container is a parameter of the docker command, it is mentioned as <container> or container id or <CONTAINER_NAME>. In all these places you can either pass a container name or container id to specify a container.

Listing containers

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
2bc9b1988080        redis               "docker-entrypoint.sh"   2 weeks ago         Up 2 hours          0.0.0.0:6379->6379/tcp    elephant-redis
817879be2230        postgres            "/docker-entrypoint.s"   2 weeks ago         Up 2 hours          0.0.0.0:65432->5432/tcp   pt-postgres

docker ps on its own only prints currently running containers. To view all containers (including stopped ones), use the -a flag:

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                    PORTS                     NAMES
9cc69f11a0f7        docker/whalesay     "ls /"                   26 hours ago        Exited (0) 26 hours ago                             berserk_wozniak
2bc9b1988080        redis               "docker-entrypoint.sh"   2 weeks ago         Up 2 hours                0.0.0.0:6379->6379/tcp    elephant-redis
817879be2230        postgres            "/docker-entrypoint.s"   2 weeks ago         Up 2 hours                0.0.0.0:65432->5432/tcp   pt-postgres

To list containers with a specific status, use the -f command line option to filter the results. Here is an example of listing all containers which have exited:

$ docker ps -a -f status=exited
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                    PORTS                     NAMES
9cc69f11a0f7        docker/whalesay     "ls /"                   26 hours ago        Exited (0) 26 hours ago

It is also possible to list only the Container IDs with the -q switch. This makes it very easy to operate on the result with other Unix utilities (such as grep and awk):

$ docker ps -aq
9cc69f11a0f7
2bc9b1988080
817879be2230

When launching a container with docker run --name mycontainer1 you give a specific name and not a random name (in the form mood_famous, such as nostalgic_stallman), and it can be easy to find them with such a command

docker ps -f name=mycontainer1

Referencing containers

Docker commands which take the name of a container accept three different forms:

TypeExample
Full UUID9cc69f11a0f76073e87f25cb6eaf0e079fbfbd1bc47c063bcd25ed3722a8cc4a
Short UUID9cc69f11a0f7
Nameberserk_wozniak

Use docker ps to view these values for the containers on your system.

The UUID is generated by Docker and cannot be modified. You can provide a name to the container when you start it docker run --name <given name> <image>. Docker will generate a random name to the container if you don't specify one at the time of starting the container.

NOTE: The value of the UUID (or a 'short' UUID) can be any length as long as the given value is unique to one container

Starting and stopping containers

To stop a running container:

docker stop <container> [<container>...]

This will send the main process in the container a SIGTERM, followed by a SIGKILL if it doesn't stop within the grace period. The name of each container is printed as it stops.

To start a container which is stopped:

docker start <container> [<container>...]

This will start each container passed in the background; the name of each container is printed as it starts. To start the container in the foreground, pass the -a (--attach) flag.

List containers with custom format

docker ps --format 'table {{.ID}}\t{{.Names}}\t{{.Status}}'

Finding a specific container

docker ps --filter name=myapp_1

Find container IP

To find out the IP address of your container, use:

docker inspect <container id> | grep IPAddress

or use docker inspect

docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${CID}

Restarting docker container

docker restart <container> [<container>...]

Option --time : Seconds to wait for stop before killing the container (default 10)

docker restart <container> --time 10

Remove, delete and cleanup containers

docker rm can be used to remove a specific containers like this:

docker rm <container name or id>

To remove all containers you can use this expression:

docker rm $(docker ps -qa)

By default docker will not delete a container that is running. Any container that is running will produce a warning message and not be deleted. All other containers will be deleted.

Alternatively you can use xargs:

docker ps -aq -f status=exited | xargs -r docker rm 

Where docker ps -aq -f status=exited will return a list of container IDs of containers that have a status of "Exited".

Warning: All the above examples will only remove 'stopped' containers.

To remove a container, regardless of whether or not it is stopped, you can use the force flag -f:

docker rm -f <container name or id>

To remove all containers, regardless of state:

docker rm -f $(docker ps -qa)

If you want to remove only containers with a dead status:

docker rm $(docker ps --all -q -f status=dead)

If you want to remove only containers with an exited status:

docker rm $(docker ps --all -q -f status=exited)

These are all permutations of filters used when listing containers.

To remove both unwanted containers and dangling images that use space after version 1.3, use the following (similar to the Unix tool df):

$ docker system df

To remove all unused data:

$ docker system prune 

Run command on an already existing docker container

docker exec -it <container id> /bin/bash

It is common to log in an already running container to make some quick tests or see what the application is doing. Often it denotes bad container use practices due to logs and changed files should be placed in volumes. This example allows us log in the container. This supposes that /bin/bash is available in the container, it can be /bin/sh or something else.

docker exec <container id> tar -czvf /tmp/backup.tgz /data
docker cp <container id>:/tmp/backup.tgz .

This example archives the content of data directory in a tar. Then with docker cp you can retrieve it.

Container logs

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

  -f, --follow=false        Follow log output
  --help=false              Print usage
  --since=                  Show logs since timestamp
  -t, --timestamps=false    Show timestamps
  --tail=all                Number of lines to show from the end of the logs

For example:

$ docker ps
CONTAINER ID    IMAGE    COMMAND                 CREATED     STATUS       PORTS
ff9716dda6cb    nginx    "nginx -g 'daemon off"  8 days ago  Up 22 hours  443/tcp, 0.0.0.0:8080->80/tcp 

$ docker logs ff9716dda6cb
xx.xx.xx.xx - - [15/Jul/2016:14:03:44 +0000] "GET /index.html HTTP/1.1" 200 511 "https://google.com" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"
xx.xx.xx.xx - - [15/Jul/2016:14:03:44 +0000] "GET /index.html HTTP/1.1" 200 511 "https://google.com" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"

Connect to an instance running as daemon

There are two ways to achieve that, the first and most known is the following:

docker attach --sig-proxy=false <container>

This one literally attaches your bash to the container bash, meaning that if you have a running script, you will see the result.

To detach, just type: Ctl-P Ctl-Q

But if you need a more friendly way and to be able to create new bash instances, just run the following command:

docker exec -it <container> bash

Copying file from/to containers

from container to host

docker cp CONTAINER_NAME:PATH_IN_CONTAINER PATH_IN_HOST

from host to container

docker cp PATH_IN_HOST CONTAINER_NAME:PATH_IN_CONTAINER

If I use jess/transmission from

https://hub.docker.com/r/jess/transmission/builds/bsn7eqxrkzrhxazcuytbmzp/

, the files in the container are in /transmission/download

and my current directory on the host is /home/$USER/abc, after

docker cp transmission_id_or_name:/transmission/download .

I will have the files copied to

/home/$USER/abc/transmission/download

you can not, using docker cp copy only one file, you copy the directory tree and the files

Remove, delete and cleanup docker volumes

Docker volumes are not automatically removed when a container is stopped. To remove associated volumes when you stop a container:

docker rm -v <container id or name>

If the -v flag is not specified, the volume remains on-disk as a 'dangling volume'. To delete all dangling volumes:

docker volume rm $(docker volume ls -qf dangling=true)

The docker volume ls -qf dangling=true filter will return a list of docker volumes names, including untagged ones, that are not attached to a container.

Alternatively, you can use xargs:

docker volume ls -f dangling=true -q | xargs --no-run-if-empty docker volume rm

Export and import Docker container filesystems

It is possible to save a Docker container's filesystem contents to a tarball archive file. This is useful in a pinch for moving container filesystems to different hosts, for example if a database container has important changes and it isn't otherwise possible to replicate those changes elsewhere. Please note that it is preferable to create an entirely new container from an updated image using a docker run command or docker-compose.yml file, instead of exporting and moving a container's filesystem. Part of Docker's power is the auditability and accountability of its declarative style of creating images and containers. By using docker export and docker import, this power is subdued because of the obfuscation of changes made inside of a container's filesystem from its original state.

docker export -o redis.tar redis

The above command will create an empty image and then export the filesystem of the redis container into this empty image. To import from a tarball archive, use:

docker import ./redis.tar redis-imported:3.0.7

This command will create the redis-imported:3.0.7 image, from which containers can be created. It is also possible to create changes on import, as well as set a commit message:

docker import -c="ENV DEBUG true" -m="enable debug mode" ./redis.tar redis-changed

The Dockerfile directives available for use with the -c command line option are CMD, ENTRYPOINT, ENV, EXPOSE, ONBUILD, USER, VOLUME, WORKDIR.