Docker Commands

Docker Commands

  • all commands start with docker then followed by a command
  • getting help
    • docker --help
  • get basic docker information
    • docker version
    • docker system info
  • command line structure
    • old version (for backward compatibility): docker <command> [options]
    • recent version: docker <command> <subcommand> [options]
    • there can be
      • short option - (single dash)
      • long option -- (double dash)

Docker Architecture

Docker architecture

Check Docker version

docker version
Client:
 Version:           27.2.0
 API version:       1.47
 Go version:        go1.21.13
 Git commit:        3ab4256
 Built:             Tue Aug 27 14:17:17 2024
 OS/Arch:           windows/amd64
 Context:           desktop-linux

Check Docker version (2)

Server: Docker Desktop 4.34.0 (165256)
 Engine:
  Version:          27.2.0
  API version:      1.47 (minimum version 1.24)
  Go version:       go1.21.13
  Git commit:       3ab5c7d
  Built:            Tue Aug 27 14:15:15 2024
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.7.20
  GitCommit:        8fc6bcff51318944179630522a095cc9dbf9f353
 runc:
  Version:          1.1.13
  GitCommit:        v1.1.13-0-g58aa920
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

Docker Account

Recent change in Docker Hub, may require to authenticate your Docker Hub's account:

docker login --username your_username
Password:
Login Succeeded

Logging in with your password grants your terminal complete access to your account.
For better security, log in with a limited-privilege personal access token. Learn more at https://docs.docker.com/go/access-tokens/

Docker Containers

Container vs Image

  • Program (binary/script)

    • application to run
    • program files with all required libraries in filesytem
  • Process

    • running instance of the application
    • program files loaded into memory

  • Image (specific format)

    • application to run
    • program files with all required libraries in filesytem
  • Container (isolated)

    • running instance of the application
    • program files loaded into memory

Manage containers

  • create
  • run
  • status
  • logs
  • stop
  • rm

Docker container - create

Create a container - nginx

We will be using the following application as an example application:

  • nginx - https://nginx.org

    • an HTTP
    • a reverse proxy server
    • a mail proxy server
    • and a generic TCP/UDP proxy server

Create a container

Create a new container.

docker container create --publish 8000:80 nginx:alpine
  • Explaination:
    • container - management command related to container
    • create - subcommand to create a new container
    • --publish 8000:80 - use host port 8000 to access port 80 in container
    • nginx:alpine - image named nginx with tag alpine

Create a container (2)

docker container create --publish 8000:80 nginx:alpine
  • docker will:

    • look for an image named nginx with tag alpine
    • if not available locally, download the image from default image registry
    • create a new container from the image

Create a container (3)

Unable to find image 'nginx:alpine' locally
alpine: Pulling from library/nginx
213ec9aee27d: Already exists
ae98275d0ecb: Pull complete
121e2d9f6af2: Pull complete
6a07d505af0f: Pull complete
3e8957b70867: Pull complete
2806408d582e: Pull complete
Digest: sha256:b433a017703c4a866c44620ed97f603555dee677756ae24df13a4329276fc0fd
Status: Downloaded newer image for nginx:alpine
4fb1731e95101606b28c5331a049501d162476287baa726c3aad23152b4298f8

The last line is the container ID of the created container.

Create a container (4)

Check the created container:

docker container list --all
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS    PORTS     NAMES
4fb1731e9510   nginx:alpine   "/docker-entrypoint.…"   4 minutes ago   Created             friendly_haslett
  • explaination:
    • list - subcommand to list containers
    • --all - list all containers (default shows only running containers)

Alternate command:

docker container ps -a

Docker container - start

Run a created container

Run the created container:

docker container start 4fb1731e9510
  • Explaination:

    • start - subcommand to start one or more stopped containers

    • 4fb1731e9510 - the container ID to run

      • can use first few characters as long as they are unique
        • e.g. 4f

Run a created container (2)

Check the started container:

docker container list --all
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS         PORTS                  NAMES
4fb1731e9510   nginx:alpine   "/docker-entrypoint.…"   10 minutes ago   Up 3 seconds   0.0.0.0:8000->80/tcp   friendly_haslett

Test the container

Test nginx container with browser using port 8000 on docker host

Nginx default homepage

Test the container (2)

Test nginx container with command line

  • e.g. curl using port 8000 on docker host
curl --head http://localhost:8000
HTTP/1.1 200 OK
Server: nginx/1.23.2
Date: Thu, 27 Oct 2022 07:15:04 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Wed, 19 Oct 2022 10:28:53 GMT
Connection: keep-alive
ETag: "634fd165-267"
Accept-Ranges: bytes

Docker container - run

Run second instance of nginx

Use run subcommand to run another instance of nginx

docker container run --publish 8001:80 --detach nginx:alpine
  • Explaination:
    • run - subcommand to run a new container
    • --publish 8001:80 - use host port 8001 to access port 80 in container
    • --detach - run container in background and print container ID

Check container status

Use ps (can also use ls, list) to see current status of containers.

docker container ps --all
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                  NAMES
1b304f8c5f78   nginx:alpine   "/docker-entrypoint.…"   28 minutes ago   Up 28 minutes   0.0.0.0:8001->80/tcp   upbeat_lamarr
4fb1731e9510   nginx:alpine   "/docker-entrypoint.…"   3 hours ago      Up 2 hours      0.0.0.0:8000->80/tcp   friendly_haslett

Run another program in the image

Run program sh in nginx image interactively.

docker container run --interactive --tty nginx:alpine sh
  • Explaination:
    • --interactive - run container and keep STDIN open even if not attached
    • --tty - allocate a pseudo-TTY

Alternate command:

docker container run -it nginx:alpine sh

Running a sh program

When running a sh program:

  • you are running a shell in a container
  • you can use only commands available in the image
  • to exit the shell (Linux container), you can type:
    • exit
    • Ctrl+D

Docker container - status

Check status of containers

To check status of all containers:

docker container ps --all
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS                     PORTS                  NAMES
258c620834e1   nginx:alpine   "/docker-entrypoint.…"   7 minutes ago   Exited (0) 7 minutes ago                          sleepy_mahavira
1b304f8c5f78   nginx:alpine   "/docker-entrypoint.…"   2 hours ago     Up 2 hours                 0.0.0.0:8001->80/tcp   upbeat_lamarr
4fb1731e9510   nginx:alpine   "/docker-entrypoint.…"   4 hours ago     Up 3 hours                 0.0.0.0:8000->80/tcp   friendly_haslett

Check resources used by containers

To check resources used by running containers:

docker container stats
CONTAINER ID   NAME               CPU %     MEM USAGE / LIMIT     MEM %     NET I/O           BLOCK I/O   PIDS
1b304f8c5f78   upbeat_lamarr      0.00%     6.371MiB / 24.76GiB   0.03%     1.22kB / 0B       0B / 0B     9
4fb1731e9510   friendly_haslett   0.00%     6.488MiB / 24.76GiB   0.03%     7.83kB / 7.52kB   0B / 0B     9

To exit, type Ctrl+C

Check process in a container

To check all process running in a container:

docker container top 4fb1731e9510
UID       PID      PPID     C      STIME     TTY     TIME         CMD
root      3328     3308     0      06:18     ?       00:00:00     nginx: master process nginx -g daemon off;
uuidd     3376     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3377     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3378     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3379     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3380     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3381     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3382     3328     0      06:18     ?       00:00:00     nginx: worker process
uuidd     3383     3328     0      06:18     ?       00:00:00     nginx: worker process

Docker container - stop

Stop a container

To stop a running container:

docker container stop 4fb1731e9510
  • Explaination:
    • stop - stop one or more running containers
    • 4fb1731e9510 - the container ID to stop

Check stopped container

Check status of the stopped container

docker container ps --all
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS                      PORTS                  NAMES
258c620834e1   nginx:alpine   "/docker-entrypoint.…"   18 minutes ago   Exited (0) 7 minutes ago    80/tcp                 sleepy_mahavira
1b304f8c5f78   nginx:alpine   "/docker-entrypoint.…"   2 hours ago      Up 2 hours ago              0.0.0.0:8001->80/tcp   upbeat_lamarr
4fb1731e9510   nginx:alpine   "/docker-entrypoint.…"   4 hours ago      Exited (0) 19 seconds ago                          friendly_haslett

Docker container - rm

To remove a container

docker container rm 258c620834e1
  • Explaination:
    • rm - remove one or more containers
    • 258c620834e1 - the container ID to remove

Note:

  • You will get an error if trying to remove a running container

Check removed container

Check status of the removed container

docker container ps --all
CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS           PORTS                  NAMES
1b304f8c5f78   nginx:alpine   "/docker-entrypoint.…"   2 hours ago   Up 2 hours ago   0.0.0.0:8001->80/tcp   upbeat_lamarr
4fb1731e9510   nginx:alpine   "/docker-entrypoint.…"   4 hours ago   2 minutes ago                           friendly_haslett

Docker Images - public images

Docker public images

You can use pre-built images from image registry.

Normally you do not need to download docker image manually.

  • if image not available locally, it will be downloaded automatically when being run

Custom Docker image

Dockerfile

To create your own image for your application

  • create a Dockerfile

A Dockerfile is a text file that contains:

  • some custom instruction (case-insensitive but usually uppercase by convention)
  • all the commands a user could call on the command line to assemble an image

Dockerfile - format

The format of a Dockerfile

# line begin with hash is treated as a comment

# one or more lines of INSTRUCTION arguments
INSTRUCTION arguments
INSTRUCTION arguments
INSTRUCTION arguments

Example 1: nginx

Example 1: Dockerfile

Simple custom image using nginx

FROM nginx:1.23.2-alpine
  • Explaination:

    • FROM - instruction to use the following image as base image

Example 1: Build image

docker image build --tag my_nginx:1 .
  • Explaination:

    • image - management command to manage images
    • build - subcommand to build an image from a Dockerfile
    • --tag - name and optionally a tag in the 'name:tag' format
    • my_nginx:1 - name the repository of this image as my_nginx with tag 1
    • . - path to context (where Dockerfile is) to be used during image building process

Example 1: Check image

To list local images on docker host:

docker image ls
  • Explaination:

    • ls - subcommand to list images

To list image from specifc repository:

docker image ls my_nginx
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
my_nginx     1         ad9ab5e40cef   8 days ago     23.6MB

Example 1: Run new image

Run a new container from the built image.

docker container run --detach --publish 8001:80 --name n1 my_nginx:1
  • Explaination:

    • --detach - run container in background and print container ID
    • --publish 8001:80 - use host port 8001 to access port 80 in container
    • --name - assign a name n1 to the container
    • my_nginx:1 - use local image with repository my_nginx with tag 1

Example 1: Test container

Test the running container.

curl http://localhost:8001

Example 2: nginx

Example 2: Dockerfile

Simple custom image using nginx: - add a web page

FROM nginx:1.23.2-alpine
COPY page.html /usr/share/nginx/html/
  • Explaination:

    • FROM - instruction to use the following image as base image
    • COPY - copy file page.html (relative to context path) to path in image

Example 2: Build image

docker image build --tag my_nginx:2 .
  • Explaination:

    • image - management command to manage images
    • build - subcommand to build an image from a Dockerfile
    • --tag - name and optionally a tag in the 'name:tag' format
    • my_nginx:2 - name the repository of this image as my_nginx with tag 2
    • . - path to context (where Dockerfile is) to be used during image building process

Example 2: Check image

To list local images on docker host:

docker image ls
  • Explaination:

    • ls - subcommand to list images

To list image from specifc repository:

docker image ls my_nginx
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
my_nginx     2         8b10604a4e5d   2 minutes ago   23.6MB
my_nginx     1         ad9ab5e40cef   8 days ago      23.6MB

Example 2: Run new image

Run a new container from the built image.

docker container run --detach --publish 8002:80 --name n2 my_nginx:2
  • Explaination:

    • --detach - run container in background and print container ID
    • --publish 8002:80 - use host port 8002 to access port 80 in container
    • --name - assign a name n2 to the container
    • my_nginx:2 - use local image with repository my_nginx with tag 2

Example 2: Test container

Test the running container.

curl http://localhost:8002/page.html

Example 3: nginx

Example 3: Run a container

Run an nginx container.

docker container run -d -p 9000:80 --name nn nginx:alpine
  • Explaination:

    • -d - run container in background and print container ID
    • -p 9000:80 - use host port 9000 to access port 80 in container
    • --name nn - assign a name nn to the container

Example 3: Copy config file

Copy the default nginx configuration file from the running container.

docker container cp nn:/etc/nginx/conf.d/default.conf .
  • Explaination:

    • cp - copy files/folders between a container and the local filesystem

Example 3: Custom config file

Modify the copied default.conf

  • move default document root to server block level
  • add new document root for request to path /app
#...
    root   /usr/share/nginx/html/;
    index  index.html index.htm;

    location / {
    }

    location /app {
        root  /;
    }
#...
}

Example 3: Dockerfile

Customise configuration of application nginx:

FROM nginx:1.23.2-alpine

RUN mkdir -p /app
COPY default.conf /etc/nginx/conf.d/
COPY page.html /app/
  • Explaination:

    • RUN - instruction to run any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

Example 3: Build image

docker image build --tag my_nginx:3 .
  • Explaination:

    • image - management command to manage images
    • build - subcommand to build an image from a Dockerfile
    • --tag - name and optionally a tag in the 'name:tag' format
    • my_nginx:3 - name the repository of this image as my_nginx with tag 3
    • . - path to context (where Dockerfile is) to be used during image building process

Example 3: Check image

To list local images on docker host:

docker image ls

To list image from specifc repository:

docker image ls my_nginx
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
my_nginx     3         568069eab905   3 minutes ago   23.6MB
my_nginx     2         8b10604a4e5d   45 hours ago    23.6MB
my_nginx     1         ad9ab5e40cef   8 days ago      23.6MB

Example 3: Run new image

Run a new container from the built image.

docker container run --detach --publish 8003:80 --name n3 my_nginx:3
  • Explaination:

    • --detach - run container in background and print container ID
    • --publish 8003:80 - use host port 8003 to access port 80 in container
    • --name n3 - assign a name n3 to the container
    • my_nginx:3 - use local image with repository my_nginx with tag 3

Example 3: Test container

Test the running container.

curl http://localhost:8003/app/page.html

Remove containers

Remove containers using their container names

docker container rm n1 n2 n3

Example 4: python

Example 4: main.py

Create a simple python file main.py with the following contents:

line = input("Enter a string: ")

digits = [ch for ch in line if ch.isdigit()]
chars = [ch for ch in line if ch.isalpha()]

s1 = " ".join(digits)
s2 = " ".join(chars)

print(f"digits: {s1}")
print(f"chars: {s2}")

Example 4: Dockerfile

FROM python:3.11-alpine
WORKDIR /app
COPY main.py /app/

# exec form
CMD ["python", "main.py"]
# shell form
#CMD python3 main.py
  • Explaination:

    • WORKDIR - instruction to set the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it
    • CMD - instruction to provide defaults for an executing container

Example 4: Build image

docker image build --tag my_app_python:1 .
  • Explaination:

    • image - management command to manage images
    • build - subcommand to build an image from a Dockerfile
    • --tag - name and optionally a tag in the 'name:tag' format
    • my_python_app:1 - name the repository of this image as my_python_app with tag 1
    • . - path to context (where Dockerfile is) to be used during image building process

Example 4: Check image

To list local images on docker host:

docker image ls

To list image from specifc repository:

docker image ls my_app_python
REPOSITORY      TAG       IMAGE ID       CREATED       SIZE
my_app_python   1         297f2a03733c   2 hours ago   51.1MB

Example 4: Run new image

Run a new container from the built image.

docker container run --interactive --tty --name p1 my_app_python:1
  • Explaination:

    • --interactiveh - keep STDIN open even if not attached
    • --tty - allocate a pseudo-TTY
    • --name p1 - assign a name p1 to the container
    • my_app_python:1 - use local image with repository my_app_python with tag 1

Example 4: Remove container

Remove container using its container name.

docker container rm p1

Example 5: java

Example 5: Main.java

Create a simple java file Main.java with the following contents:

import java.util.ArrayList; import java.util.List; import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String line = sc.nextLine();
        sc.close();
        List<String> digits = new ArrayList<>();
        List<String> chars = new ArrayList<>();
        for (char ch : line.toCharArray()) {
            if (Character.isDigit(ch)) {
                digits.add(Character.toString(ch));
            } else if (Character.isLetter(ch)) {
                chars.add(Character.toString(ch));
            }
        }
        String s1 = String.join(" ", digits);
        String s2 = String.join(" ", chars);
        System.out.println("digits: " + s1);
        System.out.println("chars: " + s2);
    }
}

Example 5: Dockerfile

FROM amazoncorretto:8-alpine-jdk as base
WORKDIR /app
COPY Main.java /app/
RUN javac Main.java

FROM amazoncorretto:8-alpine-jre as production
WORKDIR /app
COPY --from=base /app/Main.class /app/

# exec form
CMD ["java", "Main"]

# shell form
#CMD java Main

Note: Use multi-stage build

Example 5: Build image

docker image build --tag my_app_java:1 .
  • Explaination:

    • image - management command to manage images
    • build - subcommand to build an image from a Dockerfile
    • --tag - name and optionally a tag in the 'name:tag' format
    • my_app_java:1 - name the repository of this image as my_app_java with tag 1
    • . - path to context (where Dockerfile is) to be used during image building process

Example 5: Check image

To list local images on docker host:

docker image ls

To list image from specifc repository:

docker image ls my_app_java
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
my_app_java   1         62fe67987d14   48 minutes ago   110MB

Example 5: Run new image

Run a new container from the built image.

docker container run --interactive --tty --name j1 my_app_java:1
  • Explaination:

    • --interactive - keep STDIN open even if not attached
    • --tty - allocate a pseudo-TTY
    • --name j1 - assign a name j1 to the container
    • my_app_java:1 - use local image with repository my_app_java with tag 1

Example 5: Remove container

Remove container using its container name.

docker container rm j1

References