Moment For Technology

Docker Quick start

Posted on Dec. 2, 2022, 7:05 p.m. by Sophie Ward-Best
Category: The back-end Tag: The back-end docker

Docker was supposed to change the software industry when it was released in 2013, and it has changed the software industry to a certain extent.

This article mainly introduces the basic use of Docker and provides quick query of common commands. The purpose is to enable ordinary developers to have an intuitive feeling of Docker in a short time, and then quickly build a development environment with Docker.

Difficult environment configuration

I believe many friends have had such experience.

  • To learn Linux, we need to install Linux system or install Linux virtual machine;
  • If you are a backend developer, you may need to set up a PHP or Java development environment (Redis, mysql, etc.) and do the cumbersome configuration of environment variables.
  • Install a piece of software and discover that it depends on other software that needs to be installed one by one.
  • Follow a tutorial and find that your code doesn't run the same way;

Docker solves all of these environment problems by providing a consistent runtime environment.

What is a Docker

Docker started as an internal project launched by dotCloud founder Solomon Hykes in France, and it's a revolution in dotCloud's cloud services technology built on dotCloud's years. In March 2013, it opened the source code under the Apache 2.0 license agreement and maintained the main project code on GitHub.

Docker has attracted wide attention and discussion since its open source. To date, its GitHub project (opens New Window) has received more than 57,000 stars and more than 10,000 forks. In late 2013, dotCloud decided to change its name to Docker (" New Window ") due to the popularity of the Docker project.

Docker has been developed using Google's Go language, and CGroup, based on the Linux kernel, has opened new Windows. Technologies such as Namespace and OverlayFS, such as Union FS, encapsulate and isolate processes. New Window: Virtualization technology at the operating system level. Because an isolated process is independent of the host and other isolated processes, it is also called a container.

Docker has the following advantages over traditional virtual machines:

features The container The virtual machine
Start the Second level Minutes of class
The hard disk to use As a general rule, beMB As a general rule, beGB
performance Close to the native Weaker than
System support A single machine supports thousands of containers Usually dozens

The purpose of the Docker

The main uses of Docker currently fall into the following categories.

(1) Provide a consistent running environment. Ensure the consistency of the development environment, test environment, pre-development environment, and production environment to avoid bugs in specific environments.

(2) Provide resilient cloud services. Because Docker can provide a consistent running environment, we can easily implement service migration. In addition, the startup and destruction of Docker are fast, and the startup time of second level or even millisecond level can be achieved, and rapid capacity expansion and reduction can be achieved.

3) Continuous delivery and deployment. For DevOps workers, Docker enables continuous integration, delivery and deployment through custom application images. Developers build images from Dockerfile and test their Integration with Continuous Integration new Window, while operations can quickly deploy the images directly into production. Even automatic Deployment in conjunction with the Continuous Delivery/Deployment system has been opened.

(4) Build a micro-service architecture. On a single server, or on our own laptop, we can run multiple services, including back-end resources that the service depends on, such as Redis, mysql, Kafka, etc. We can even deploy these backend resources in a cluster. With Docker we can simulate a microservice architecture on a single machine.

Install the Docker

For the installation of Docker, refer to the official documentation.

  • Mac
  • Windows
  • Ubuntu
  • Debian
  • CentOS
  • Fedora
  • Other Linux distributions

Docker also offers a desktop version.

Mirror Image (Image)

Docker image is a special file system. In addition to providing programs, libraries, resources, configuration and other files required by the container runtime, Docker image also contains some configuration parameters (such as anonymous volume, environment variables, users, etc.) prepared for the runtime. The mirror does not contain any dynamic data, and its contents are not changed after the build.

Docker images are stored in layers. When images are built, they will be built layer by layer. The former layer is the foundation of the latter layer. Different images can be reused to save storage space.

Developers can create their own images, or they can use good ones made by others. In general, the more commonly used images can be found on the official repository Docker Hub.

The command to obtain images from the Docker image repository is Docker pull. The command format is:

$docker pull [option] [Docker Registry address [: port number]/] Repository name [: tag]Copy the code
  • Docker image warehouse address: The format of the address is generally domain /IP[: port number]. The default address is Docker Hub(docker.io).
  • Warehouse name: As stated earlier, the warehouse name here is a two-paragraph name, i.e User name / Software name . For Docker Hub, if the user name is not given, the default islibrary"Is the official mirror image.
➜ ~ Docker pull Ubuntu :20.04 20.04: Pulling from library/ Ubuntu a31C7b29f4ad: pull complete Digest: sha256:b3e2e47d016c08b3396b5ebe06ab0b711c34e7f37b98c9d37abe794b71cea0a2 Status: Downloaded newer imageforUbuntu: 20.04 docker. IO/library/ubuntu: 20.04Copy the code

The above command pulls the Ubuntu 20.04 image from the official repository. The last line is the full name of the image.

In the same way, let's install the redis and mysql-server images again.

➜  ~ docker pull redis:latest
latest: Pulling from library/redis
33847f680f63: Pull complete
26a746039521: Pull complete
18d87da94363: Pull complete
5e118a708802: Pull complete
ecf0dbe7c357: Pull complete
46f280ba52da: Pull complete
Digest: sha256:cd0c68c5479f2db4b9e2c5fbfdb7a8acb77625322dd5b474578515422d3ddb59
Status: Downloaded newer image forRedis: latest docker. IO/library/redis: latest ➜ ~ docker pull mysql/mysql - server: 5.7 5.7: Pulling from mysql/mysql-server b5be27e1996f: Pull complete 091844bfb0ec: Pull complete 3cb5fb55841d: Pull complete 47644b99acea: Pull complete 3bd4cb0b78d1: Pull complete a62c52d3a764: Pull complete 20396840d0b1: Pull complete 38b3da6a86f7: Pull complete Digest: sha256:779c5ba746fe052579c50a0533eaf38ee1ab75d348534d5db092028242a32eed Status: Downloaded newer imageforMysql/mysql - server: 5.7 docker. IO/mysql/mysql - server: 5.7Copy the code

Actually measured, the official image of the pull speed is ok, if you download from the official image is slow, you can use the mirror accelerator.

The image we just pulled is also visible in the desktop Docker.

If you don't like the command line, you can manage the image, start the container, and so on.

Mirroring operations

List the mirror

➜ ~ docker image ls REPOSITORY TAG image ID CREATED SIZE redis latest aa4d65e670d6 39 hours ago 105MB mysql/mysql-server 5.7 8b7280d401C0 4 Days ago 385MB Ubuntu 20.04c29284518f49 11 Days ago 72.8MBCopy the code

The list contains the warehouse name, label, image ID, creation time, and occupied space.

View the space occupied by a mirror

➜  ~ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          3         0         563MB     563MB (100%)
Containers      0         0         0B        0B
Local Volumes   0         0         0B        0B
Build Cache     0         0         0B        0B
Copy the code

You can use the docker system df command to easily view the space occupied by images, containers, and data volumes. Because we haven't started the mirror yet, everything else is 0.

Remove the mirror

To delete a local image, use the docker image rm command. The format is:

$docker image rm [options]  image 1 [ image 2...]Copy the code

mirror can be the short ID of the mirror, the long ID of the mirror, the name of the mirror or the summary of the mirror.

For example, we can use the command dokcer image rm redis or docker image rm aa4 to delete the redis image.

➜  ~ docker image rm redis
Untagged: redis:latest
Untagged: [email protected]:cd0c68c5479f2db4b9e2c5fbfdb7a8acb77625322dd5b474578515422d3ddb59
Deleted: sha256:aa4d65e670d6518e5da96ca9d1a76370a942970a8802e6d5cc6bcf058ab12ca7
Deleted: sha256:3bd00d38f5ca70200050477c527cc60cfdf82911d6fe03932e2bcae31a95cfa2
Deleted: sha256:22722fde392d188cfbe5bbd0c2451cc71cf5b000afc0e5114c1066bb5e113ec9
Deleted: sha256:38212b55ef525e86cd726cd83c1a82a6009c68d24771d6e93d439fdc88e66f0e
Deleted: sha256:188c498579cef37b65a93d6448c6b129fa07d5740fc213a18843ff22d80cd10d
Deleted: sha256:2117165cd53c98f13ec7af36c9d8acd239fc541c847efaccb49885decf615d68
Deleted: sha256:814bff7343242acfd20a2c841e041dd57c50f0cf844d4abd2329f78b992197f4
Copy the code

After deleting the Redis image, we still need it, ok, then we will install it back.

Custom image

A Dockerfile is a text file that contains lines of instructions, each of which builds a layer, so the content of each instruction describes how the layer should be built.

Next, let's build an image using two small games on the Linux command line as an example.

step 1

Create a new sound. TXT file and write a few words in it.

step 2

Create a new file named Dockerfile and write the following command:

FROM Ubuntu :20.04 COPY./sound. TXT/WORKDIR/RUN apt-get update  apt-get-y install sl  apt-get-y install cowsay echo "export PATH=/usr/games:$PATH"  /etc/bash.bashrc
Copy the code

While FROM specifies the base image, the image we built is based on Ubuntu :20.04.

COPY copies sound.txt from the current directory to the root directory of the build image.

WORKDIR / : Specifies the next work path as /.

The next RUN command is to RUN the bash command of Linux to install sl and cowsay. By default, they are installed in /usr/games, so we add /usr/games to PATH.

step 3

Run the docker build command to build the image.

➜ Documents docker build-t ubuntu-game:0.1. [+] Building 0.3s (8/8) FINISHED = [internal] Load build definition from Dockerfile transferrable = = transferrable Dockerfile: 37B 0.2s = [internal] load. Dockerignore 0.1s = = transferring-context: 2B 0.1s = [internal] load metadataforDocker. IO/library/ubuntu: 20.04 0.0 s =  (internal) load build context 0.0 s =  =  transferring context: 30 b 0.0 s =  (1/4) FROM docker. IO/library/ubuntu: 20.04 0.0 s =  CACHED (2/4). COPY/sound. TXT / 0.0 s =  CACHED (3/4) of the RUN Apt-get update  apt-get-y install sl  apt-get-0.0s = layer 0.0s = layer 0.0s = layer 0.0s = layer 0.0s = layer 0.0s Their image sha256:9535 c4b11c3ffdd60225167968f9af8e5a69cf1d5df85 0.0 s =  =  naming the to Docker. IO/library/ubuntu - game: 0.1Copy the code

The dot following the docker build command is used to specify the current directory as the path to the build context.

After running the build command successfully, use the Docker image ls command to see the ubuntu-Game image we built.

step 4

Let's see what happens.

Docker run --name game-it Ubuntu-game :0.1Copy the code

Starting the image with the above command takes you to the Ubuntu-Game terminal and will be explained in more detail in the next section on containers.

In the root directory is the sound.txt file that we created.

[email protected]:/# ls -l sound.txt
-rw-r--r-- 1 root root 49 Jul 25 05:05 sound.txt
Copy the code

Run source. bashrc to make the environment variables take effect.

Execute the following command, and the cowsay game is started. You can see that a cow recites a poem by Du Fu. For more on cowsay, see Cowsay.

[email protected]:/# cat sound.txt | cowsayThe wind is swift, the sky is high, the ape is howling, and the white bird is flying back. / -- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||Copy the code
[email protected]:/# sl
Copy the code

Execute the SL command, and a train will rumble past the terminal from left to right, with white smoke.

The container

Simply put, a container is a single application or set of applications that are running independently of each other and the environment in which they are running. In contrast, a virtual machine can be understood to simulate a complete operating system running (providing the runtime environment and other system environments) and the applications running on it.

Start the container

For example, the following command outputs a "Hello World" and then terminates the container.

➜  ~ docker run ubuntu:20.04 /bin/echo 'Hello world'
Hello world
Copy the code

This is almost indistinguishable from running /bin/echo 'hello world' locally.

The following command starts a bash terminal and allows users to interact.

➜  ~ docker run -t -i ubuntu:20.04 /bin/bash
[email protected]:/#
Copy the code

The -t option lets Docker assign a pseudo-tty and bind it to the container's standard input, while the -i option keeps the container's standard input open.

In interactive mode, the user can enter commands through the created terminal, for example

[email protected]:/# ls
bin   dev  home  lib32  libx32  mnt  proc  run   srv  tmp  var
boot  etc  lib   lib64  media   opt  root  sbin  sys  usr
Copy the code

Use the Docker ps or docker container ls command to see which containers are running.

➜ ~ Docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1d52BB27322e Ubuntu :20.04"/bin/bash"   2 minutes ago   Up 2 minutes             pensive_bouman
Copy the code

Run the docker ps -a or docker container ls -a command to view all containers, including those that have been stopped.

➜ ~ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1d52BB27322e Ubuntu :20.04"/bin/bash"5 minutes ago Exited (0) 6 seconds ago pensive_bouman 24604b36f7e8 Ubuntu :20.04Settlement "/ bin/echo" Hello..."5 minutes ago Exited (0) 5 minutes ago Practical_shtern 98e83032d71c Ubuntu-game :0.1"bash"                   19 minutes ago   Exited (0) 11 minutes ago             game
Copy the code

Can you start a container that has been stopped? The answer is yes.

Use the docker container start command to start an exited container directly.

➜  ~ docker start 24
Copy the code

The above command to start a container can omit container. 24 indicates a short summary of the id of the container to start. A longer summary of the container or the name of the container can also be used.

The container runs in the background and enters the container

You need to let Docker run in the background rather than directly output the results of executing commands in the current host. This can be done by adding the -d parameter.

For example, let's start a mysql container in the background.

➜  ~ docker image ls mysql/mysql-server
REPOSITORY           TAG       IMAGE ID       CREATED      SIZE
mysql/mysql-server   5.7       8b7280d401c0   4 days ago   385MB
Copy the code

We have already installed the image of mysql-server, now start it up.

➜ ~ docker run - name mysql - d mysql/mysql - server: 5.7 9 f6e2fd2501306db7ade6b940f11f3c3e7f0495976447541742e1de9481f9c7e ➜ ~ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 9f6e2FD25013 mysql/mysql-server:5.7"/ entrypoint. Sh mysql..."   4 seconds ago   Up 2 seconds (health: starting)   3306/tcp, 33060/tcp   mysql
Copy the code

This command starts the mysql-server container and gives it the name mysql.

We can also stop this container.

docker stop mysql
Copy the code

Restart the container. The docker Container restart command terminates a running container and then restarts it.

To obtain the output information of the container running in the background, you can run the docker container logs command.

To enter a container running in the background, use the exec command.

Docker exec can be followed by multiple parameters, here mainly explains the -i -t parameter.

When only the -i parameter is used, the interface does not have the familiar Linux command prompt because no pseudo terminal is assigned. However, the command execution result can still be returned.

When the -i -t parameter is used together, you see the familiar Linux command prompt.

Remove the container

You can use Docker Container RM to remove a container that is in the terminated state. For example,

➜  ~ docker container rm mysql
mysql
Copy the code

To remove a running container, add the -f argument. Docker sends a SIGKILL signal to the container.

Use the docker container ls -a command to view all the containers that have been created and are in the terminated state. If there are too many containers to delete one by one, it may be troublesome. Use the following command to clear all the containers in the terminated state.

➜  ~ docker container prune
Copy the code

example

To run the mysql server

Installing an image:

docker pull mysql/mysql-server
Copy the code

Start the container:

Docker run --name=mysql -d -p 3306:3306 mysql/mysql-server:5.7Copy the code

-p 3306:3306 refers to the mapping of the container port 3306 to the local port 3306. With the port mapping, we can use mysql client to access mysql locally.

Run redis

Install an image and pull the latest Redis image from the official image.

docker pull redis
Copy the code

Start the container:

docker run --name redis -d -p 6379:6379 redis
Copy the code

-p 6379:6379 maps the container port 6379 to the local port 6379.

Run the consul

Install an image, and pull the latest image from the official image consul.

docker pull consul
Copy the code

Start the container:

docker run --name consul -d -p 8500:8500 -p 8600:8600/udp consul
Copy the code

The above command maps ports 8500 and 8600 to the local.

Run the kafka

Since Kafka relies on Zookeeper, we use Docker Compose to pull the image.

Save the following yML configuration as a file named docker-compose. Yml, and run the docker-compose up command in the path of the file to install the ZooKeeper and Kafka images and start the corresponding containers.

version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - 22181: 2181
  
  kafka:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    ports:
      - 29092: 29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
Copy the code

The mirror pull process is as follows.

➜ docker compose up [+] Running 15/15 ⠿ zookeeper Pull 72.1s ⠿ 96965a3a8424 Pull complete 12.8s ⠿ eb918a808c15 Pull Complete 58.2s ⠿ 5c2fffeabbf7 Pull complete 58.5s ⠿ b479bf09eedc Pull complete 60.2s ⠿ 2e31c2ab64ea Pull complete 60.5s ⠿ e5161e1fdbdc Pull complete 66.4s ⠿ 5dcd26e8f603 Pull complete 66.5s ⠿ 27267efe7f14 Pull complete 66.6s ⠿ kafka Pull 71.6s ⠿ 4d0d850cd4ad Pull complete 13.1s ⠿ 7a73120408f4 Pull complete 53.5s ⠿ 68bcf2239ce4 Pull complete 60.1s ⠿ E0f07497560d Pull complete 65.8s ⠿ b88780ca570c Pull complete 66.2s [+] Running 3/3 ⠿ Network documents_default Created 1.7s ⠿ Container Documents_zookeeper_1 s... 2.6s ⠿ Container Documents_kafka_1 Start... 3.8 sCopy the code

conclusion

  • Docker can help us quickly build a consistent environment;
  • Docker's flexible scaling makes it ideal for microservices;
  • This paper introduces the concept of mirror and container and related operations.
  • Examples of using containers to quickly build mysql, Redis and other back-end resources are presented.
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.