Beginner’s Guide to Docker

Before using the [cSphere] (https://csphere.cn) platform, it is essential to understand the basic knowledge of Docker. This is targeted at users who already have a certain level of Linux knowledge.

## What is Docker

Docker is an advanced container technology. The specific “advancement” is reflected in the fact that Docker introduces images for containers, allowing containers to be created from predefined templates (images), and this template is layered.

### Commonly Mentioned Features of Docker:

– Lightweight, reflected in low memory usage and high density

– Fast, millisecond startup

– Isolation, sandbox technology is more like a virtual machine

### Basic Technologies of Docker:

– Namespace, the basis for container isolation, ensuring that Container A cannot see Container B. There are six namespaces: User, Mnt, Network, UTS, IPC, Pid

– Cgroups, container resource statistics and isolation. The main cgroups subsystems used are: cpu, blkio, device, freezer, memory

– Unionfs, typical: aufs/overlayfs, the basis for layered images

### Docker Components:

– **Docker Client** ———> initiates requests to the Docker server process, such as creating, stopping, and destroying containers.

– **Docker Server** ———> processes all Docker requests and manages all containers.

– **Docker Registry** ———> a central repository for storing images, can be considered as a binary SCM.

## Docker Installation ##

Installing Docker is very simple, supporting all mainstream operating systems, from Mac to Windows to various Linux distributions.

For details, refer to: [Docker Installation](https://docs.docker.com/installation/)

## Common Docker Commands ##

#### Container Related Operations

– docker create # Create a container but do not start it

– docker run # Create and start a container

– docker stop # Stop a container, sending SIGTERM signal

– docker start # Start a stopped container

– docker restart # Restart a container

– docker rm # Remove a container

– docker kill # Send a signal to a container, default SIGKILL

– docker attach # Connect (enter) to a running container

– docker wait # Block until a container stops running

#### Get Container Related Information

– docker ps # Show running (Up) containers

– docker ps -a # Show all containers, including running (Up) and exited (Exited)

– docker inspect # Get all information about a container in-depth

– docker logs # View the container’s logs (stdout/stderr)

– docker events # Get real-time events from the Docker server

– docker port # Show port mappings of a container

– docker top # Show process information of a container

– docker diff # Show changes in the container’s filesystem

#### Exporting Containers

– docker cp # Copy files or directories from a container to the host

– docker export # Export the entire filesystem of a container as a tar package, without layers, tags, etc.

#### Executing Commands

– docker exec # Execute a command in a container, can run bash for interactive mode

#### Image Operations

– docker images # Show the list of all local images

– docker import # Create an image from a tar package, often used in conjunction with export

– docker build # Create an image using Dockerfile (recommended)

– docker commit # Create an image from a container

– docker rmi # Remove an image

– docker load # Create an image from a tar package, used in conjunction with save

– docker save # Save an image as a tar package, with layers and tag information

– docker history # Show the historical commands used to create an image

– docker tag # Assign an alias to an image

#### Registry Operations

– docker login # Log into a registry

– docker search # Search for images in the registry

– docker pull # Download an image from the registry to the local

– docker push # Push an image to the registry

#### Get Container IP Address (Container status must be Up)

docker inspect id | grep IPAddress | cut -d ‘”‘ -f 4

#### Get Port Mapping

docker inspect -f ‘{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}’ id

#### Get Environment Variables

docker exec container_id env

#### Kill All Running Containers

docker kill $(docker ps -q)

#### Remove Old Containers (Created more than a week ago)

docker ps -a | grep ‘weeks ago’ | awk ‘{print $1}’ | xargs docker rm

#### Remove Stopped Containers

docker rm `docker ps -a -q`

#### Remove All Images, Be Careful

docker rmi $(docker images -q)

## Dockerfile

Dockerfile is the basis for building images in Docker, and it is also an important feature that distinguishes Docker from other containers. It is precisely because of Dockerfile that the automation and portability of Docker become possible.

Whether in development or operation, learning to write Dockerfile is almost essential, as it helps you understand the operation of the entire container.

#### FROM <image name>, build a new image from a base image

FROM ubuntu

#### MAINTAINER <author name>, maintainer information

MAINTAINER William <[email protected]>

#### ENV <key> <value>, set environment variables

ENV TEST 1

#### RUN <command>, run shell commands non-interactively

RUN apt-get -y update

RUN apt-get -y install nginx

#### ADD <src> <dst>, copy external files into the image, src can be a URL

ADD http://nicescale.com/ /data/nicescale.tgz

#### WORKDIR /path/to/workdir, set working directory

WORKDIR /var/www

#### USER <uid>, set user ID

USER nginx

#### VOLUME <#dir>, set volume

VOLUME [‘/data’]

#### EXPOSE <port>, expose which ports

EXPOSE 80 443

#### ENTRYPOINT [‘executable’, ‘param1′,’param2’] execute command

ENTRYPOINT [“/usr/sbin/nginx”]

#### CMD [“param1″,”param2”]

CMD [“start”]

This command is executed when creating and starting a container. If ENTRYPOINT is set, CMD will be used as parameters </usr/sbin/nginx start>

#### Best Practices for Dockerfile

– Try to place some common and unchanging instructions at the top

– Prefer using JSON array format for CMD and ENTRYPOINT

#### Build image through Dockerfile

docker build csphere/nginx:1.7 .

## Registry

After the image is built from Dockerfile, it needs to be pushed (push) to the image registry. Enterprises need to build a private Docker registry, which can be considered as a binary SCM, and CI/CD also needs to revolve around the registry.

#### Deploying Registry

mkdir /registry

docker run -p 80:5000 -e STORAGE_PATH=/registry -v /registry:/registry registry:2.0

#### Pushing Images to the Registry

Assuming 192.168.1.2 is the address of the registry:

docker tag csphere/nginx:1.7 192.168.1.2/csphere/nginx:1.7

docker push 192.168.1.2/csphere/nginx:1.7

## A Few Simple Examples

### Container Operations

1. Create and pull busybox

# docker run -it –name con01 busybox:latest

/ # ip addr # Execute inside the container

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default

link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

inet 127.0.0.1/8 scope host lo

valid_lft forever preferred_lft forever

Segmentation fault (core dumped)

/ # ping www.csphere.cn

PING www.csphere.cn (117.121.26.243): 56 data bytes

64 bytes from 117.121.26.243: seq=0 ttl=48 time=3.139 ms

64 bytes from 117.121.26.243: seq=1 ttl=48 time=3.027 ms

^C

— www.csphere.cn ping statistics —

2 packets transmitted, 2 packets received, 0% packet loss

round-trip min/avg/max = 3.027/3.083/3.139 ms

exit # Exit the container

2. Create a test container

docker run -d –name con03 csphere/test:0.1

efc9bda4a2ff2f479b18e0fc4698e42c47c9583a24c93f5ce6b28a828a172709

3. Log into con03

# docker exec -it con03 /bin/bash

[root@efc9bda4a2ff /]# exit

4. Stop con03

# docker stop con03

con03

5. Start con03

# docker start con03

con03

6. Remove con03

“`

# docker ps -a

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

efc9bda4a2ff csphere/test:0.1 “/usr/local/bin/run 4 minutes ago Up 17 seconds con03

99aa6ee25adc busybox:latest “/bin/sh” 14 minutes ago Exited (0) 12 minutes ago con02

831c93de9b9f busybox:latest “/bin/sh” 2 hours ago Up 27 minutes con01

# docker rm con02 # Container is in stopped state

# docker rm -f con03 # Container is in running state

“`

### Image Operations

1. Pull an image from Docker Hub official image repository

# docker pull busybox:latest

atest: Pulling from busybox

cf2616975b4a: Pull complete

6ce2e90b0bc7: Pull complete

8c2e06607696: Already exists

busybox:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.

Digest: sha256:38a203e1986cf79639cfb9b2e1d6e773de84002feea2d4eb006b52004ee8502d

Status: Downloaded newer image for busybox:latest

2. Upload an image from local to the image repository

docker push 192.168.1.2/csphere/nginx:1.7

3. Search for a specific image in the image repository

# docker search centos/nginx

NAME DESCRIPTION STARS OFFICIAL AUTOMATED

johnnyzheng/centos-nginx-php-wordpress 1 [OK]

sergeyzh/centos6-nginx 1 [OK]

hzhang/centos-nginx 1 [OK]

4. View the list of local images

# docker images

TAG IMAGE ID CREATED VIRTUAL SIZE

docker.io/csphere/csphere 0.10.3 604c03bf0c9e 3 days ago 62.72 MB

docker.io/csphere/csphere latest 604c03bf0c9e 3 days ago 62.72 MB

csphere/csphere 0.10.3 604c03bf0c9e 3 days ago 62.72 MB

registry 2.0 2971b6ce766c 7 days ago 548.1 MB

busybox latest 8c2e06607696 3 weeks ago 2.43 MB

5. Remove an image

docker rmi busybox:latest # Cannot delete if a container is using this image, an error will occur

FATA[0000] Error: failed to remove one or more images

docker rmi -f busybox:latest # Force remove if container is in Exited state

6. View the commands used to build the image

# docker history busybox:latest

IMAGE CREATED CREATED BY SIZE

8c2e06607696 3 weeks ago /bin/sh -c #(nop) CMD [“/bin/sh”] 0 B

6ce2e90b0bc7 3 weeks ago /bin/sh -c #(nop) ADD file:8cf517d90fe79547c4 2.43 MB

cf2616975b4a 3 weeks ago /bin/sh -c #(nop) MAINTAINER Jérôme Petazzo 0 B

This article was shared by:

Zhang Chun Yuan, working at Xi Yun cSphere, expert in Xi Yun Docker open-source free training courses. One of the earliest Docker practitioners in China.

Beginner's Guide to Docker

Leave a Comment

×