Technotes

Technotes for future me

Docker

Docker

Run an image with an ENTRYPOINT command in interactive mode with the command /bin/bash

docker run --entrypoint /bin/bash -i -t <image_name>
docker run --entrypoint /bin/bash -i -t ghcr.io/blaat/toolbox:1.0.0

Stop a Docker container

The docker stop command stops running Docker containers.
To stop a container it sends the SIGTERM signal to the main process inside a Docker container requesting it to terminate.
If the main process inside a container is not terminated after a grace period, the docker stop command sends the SIGKILL signal to cause it to terminate immediately.
In this post i am showing an example of how to stop a Docker container and also how to stop all running Docker containers.

docker ps

docker stop 72ca2488b353

Stop all Docker containers

docker stop $(docker ps -a -q)

Remove Container – Remove All Containers

To delete a particular Docker container firstly you have to find out the CONTAINER ID or NAME by listing the all Docker containers.
When the container for deletion is identified it can be removed with the docker rm command.
From the command-line it is also possible to remove stopped (unused) Docker containers only or, if it is needed, you can force removal of the all Docker containers.

List running Docker containers:

docker ps

List all Docker containers:

docker ps -a

Remove Docker container by CONTAINER ID or NAME:

docker rm <container>

Force removal of a running Docker container:

docker rm -f <container>

Remove all stopped (unused) Docker containers:

docker container prune -f

Force removal of the all Docker containers, including running containers:

docker rm -f $(docker ps -a -q)

Remove Image – Remove All Images – Remove Unused

To delete a particular Docker image firstly you have to find out the IMAGE ID by listing the all local Docker images.
When the image for deletion is identified it can be removed with the docker rmi command.
From the command-line it is also possible to remove unused Docker images (not used by any containers) or, if it is needed, you can force removal of the all locally downloaded Docker images.

List all locally downloaded Docker images:

docker images

Remove Docker image by IMAGE ID:

docker rmi <image>

Force removal of the Docker image:

docker rmi -f <image>

Remove all unused Docker images:

docker image prune -a -f

Force removal of the all Docker images:

docker rmi -f $(docker images -q)

Check Docker Container Logs

Check the logs of a Docker container:

docker logs container

Show the Docker container logs with timestamps:

docker logs container --timestamps

Show Docker logs since particular date:

docker logs container --since YYYY-MM-DD

Show Docker logs since particular time:

docker logs container --since YYYY-MM-DDTHH:MM

Tail Docker Logs

tail the last N lines of logs:

docker logs container --tail N

tail -f (follow) the Docker container logs:

docker logs container --follow

Docker Container Logs Location

Find out where the Docker container logs are stored:

docker inspect --format='{{.LogPath}}' container

Enter Container

The docker exec command serves for executing commands in running Docker containers.
With this command it is also possible to enter a running Docker container and start a bash session.
In this post i am showing how to enter a Docker container and execute an interactive bash shell inside it.

Enter a Docker container by name or ID and start a bash shell:

docker exec -it 72ca2488b353 bash

If the bash shell is not found, you will get the message as follows:
oci runtime error: exec failed: container_linux.go:265: starting container process caused “exec: \”bash\”: executable file not found in $PATH”
In this case you can enter a Docker container and start a simple sh shell:

docker exec -it 72ca2488b353 sh

Commands

Note <container> is either a container id, or a container name (if such is given to a container with the –name option on start). Both can be obtained with the “docker ps -a” command. is either an image id, or an image name. Both can be obtained with the “docker image” command. Do not confuse with container id/name!

    docker ps                           # List running instances
    docker exec -it <container> bash    # Log into container bash environment
    docker ps -a                        # List all instances
    docker inspect <container>          # Instance details
    docker top     <container>          # Instance processes
    docker logs    <container>          # Instance console log
    docker port    <container>          # Shows container's port mapping. The same can be seen with "docker ps" though (row - "PORTS")
    docker diff    <container>          # Shows changes on container's filesystem. Will produce a list of files and folders prefixed by a
                                        # character. "A" is for "added", "C" is for changed.
    docker stats   <container>          # Shows the consumed by the container resources (memory, CPU, network bandwidth)
    docker export --output="latest.tar" <container> #Export a container’s filesystem as a tar archive
    docker network create --subnet=172.18.0.0/16 elknet #Create a network
    docker run --net elknet --ip 172.18.0.22 -it ubuntu bash #Assign static IP from network

Building Images

    docker build .
    docker build -f Dockerfile.test .                     # Use another Dockerfile file name
    docker build --target <stage> .                       # Build specific target of a multi-stage Dockerfile
    docker build --build-arg MYARG=myvalue .              # Pass variables with --build-arg
    docker build --add-host <hostname>:<target> .         # Inject hostnames

Releasing Images

    docker tag <source>[:<tag>] <target>:<tag>
    docker push <target>:<tag>

To a private/remote registry

    docker tag <source>[:<tag>] <remote registry>/<target>:<tag>
    docker push <remote registry>/<target>:<tag>

Container Lifecycle

    docker run -i -t ubuntu /bin/bash   # New instance from image. "-i" is for "interactive" and "t" is for terminal. Without "it" it
                                        # won't be interactive - you will get a shell/terminal, but will not be able to type anything onto
                                        # it. Without "t" you will not get a terminal opened. The command will run and exit.

    docker run -i -t --rm ubuntu /bin/bash # If you need a one-time container, then use the --rm option. Thus, once you exit the container,
                                        # it will be removed


    docker start   <container>
    docker restart <container>
    docker stop    <container>
    docker attach  <container>
    docker rm      <container>          # Removes / deletes a container (do not confuse with the "rmi" command - it removes an image!).
                                        # The container must be stopped in beforehand.

    docker cp '<id>':/data/file .       # Copy file out of container

    docker images                       # List locally stored images
    docker rmi <image>                  # Removes / deletes a locally stored image
    docker save -o <tarball> <image>    # Saves a local image as a tarball, so you can archive/transfer or inspect its content
                                        # Example: docker save -o /tmp/myimage.tar busybox
    docker history <image>              # Shows image creation history. Useful if you want to "recreate" the Dockerfile of an image -
                                        # in cases where you are interested how the image has been created.

Dockerfile Examples

Installing packages

    FROM debian:wheezy
    RUN apt-get update
    RUN apt-get -y install python git

Adding users

```bash
    RUN useradd jsmith -u 1001 -s /bin/bash

Defining work directories and environment

    WORKDIR /home/jsmith/
    ENV HOME /home/jsmith

Mounts

    VOLUME ["/home"]

Opening ports

    EXPOSE 22
    EXPOSE 80

Start command

    USER jsmith
    WORKDIR /home/jsmith/
    ENTRYPOINT bin/my-start-script.sh

Setting timezone

    ENV TZ=America/Los_Angeles
    RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

Using variables

    RUN curl $JAR_DOWNLOAD
    ...
    CMD java ${JAVA_OPTS} ...

Pass those variables using --build-arg JAR_DOWNLOAD=... --build-arg JAVA_OPTS="-D..."

For longer commands use CMD array syntax

    CMD [ "java", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseCGroupMemoryLimitForHeap", <...>]

Ensure pipe errors to break the build

    SHELL ["/bin/bash", "-o", "pipefail", "-c"]

Clear apt cache

    RUN apt-get update \
      && apt-get install --no-install-recommends -y <packages> \
      && apt-get clean \
      && rm -rf /var/lib/apt/lists/*

Working with private registries

In Dockerfile use syntax with /

    FROM <server>/<image>:<tag>

Define a variable registry in FROM clause and pass the hostname with --build-arg MY_REGISTRY=docker.example.com

    ARG MY_REGISTRY=
    FROM ${MY_REGISTRY}/myimage

Multi-stage Dockerfiles

Starting with Docker 17.05 you can do multi-stage builds by having multiple FROM commands in one Dockerfile

    FROM image1
    ...

    FROM image2
    ...

Above syntax example will automatically trigger two builds. Stages also can be named:

    FROM image1 as stage1

and explicitely called on the CLI

    docker build --target stage1 ...

Docker Registry v2 API

https://docs.docker.com/registry/spec/api/

    /v2/_catalog                # List repositories
    /v2/<repository>/tags/list  # List tags for a given repo

Misc

Best Practices for Images

  • When using ext4: disable journaling
docker logs -f c2
docker exec -it 4e /bin/bash
docker ps
docker run my_image -it bash
docker logs --follow my_container
docker volume ls
docker rm my_container
docker rmi my_image
docker stop my_container
docker kill my_container
docker kill $(docker ps -q)
docker rm $(docker ps -a -q)
docker rmi $(docker images -q)

https://github.com/wsargent/docker-cheat-sheet https://github.com/eon01/DockerCheatSheet https://github.com/FuriKuri/docker-best-practices

Last updated on 10 Apr 2022
Published on 22 Jan 2020
Edit on GitHub