A taste of Docker

Original link: http://weepingdogel.github.io/posts/%E6%B5%85%E5%B0%9Ddocker/

wallhaven-d5we7o.png

sequence

Well, plan ahead and learn how to play docker in advance.

roll them to death

what is docker?

Official English Introduction
Docker is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly. With Docker, you can manage your infrastructure in the same ways you manage your applications. By taking The advantage of Docker’s methodologies for shipping, testing, and deploying code quickly, you can significantly reduce the delay between writing code and running it in production.

According to the official documentation and popular understanding, docker can provide a container for rapid deployment of software projects. It is equivalent to a virtual machine that can simulate the environment required by the project, but it is different from the general virtual machine we understand.

The general virtual machine needs to install the entire operating system, which will occupy a lot of resources on our computer, while docker only needs to simulate the running environment required by the project, and the occupancy rate is very low, which can greatly improve the development efficiency.

It can simulate the software environment according to our needs, and can quickly deploy our developed project instances (such as Mastodon), and to a certain extent, it has the function of environment isolation, the operating environment is separated from the operating system, and can run multiple container.

And we can encapsulate the container into an image for repeated use.

Like this whale in a container, it swims out of the box wherever it goes.

how to install docker

Installing docker on each platform is very simple.

The Linux platform may be a little more difficult for beginners, but for familiar users, installing docker on Linux is very fast.

Just install it directly from the package manager of the appropriate distribution.

Arch

For example, we Arch can ask pacman to bring this whale back.

 1
 sudo pacman -S docker
Notice

If the following error occurs when running

 1 2
 docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?. See 'docker run --help'.

Please use systemctl to start the system process of docker .

 1
 sudo systemctl start docker

If necessary, set it to start automatically

 1
 sudo systemctl enable docker

Debian

If you are using a deb-based distribution, you can refer to the official documentation to install it with apt.

Set up warehouse

  1. Update the apt repository and install some dependencies to allow apt to use third-party repositories over https.
 1
 sudo apt update
 1
 sudo apt install ca-certificates curl gnupg lsb-release
  1. Add Docker official GPG key
 1
 sudo mkdir -p /etc/apt/keyrings
 1
 curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  1. Set up a Docker repository
 1 2 3
 echo \ "deb [arch= $( dpkg --print-architecture ) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \  $( lsb_release -cs ) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

install docker

  1. Update package repository
 1
 sudo apt update

If a GPG error occurs during the update, you can refer to this tip on the official website:

Receiving a GPG error when running apt-get update?

Your default umask may be incorrectly configured, preventing detection of the repository public key file. Try granting read permission for the Docker public key file before updating the package index:

 1 2 3
 $ sudo chmod a+r /etc/apt/keyrings/docker.gpg  $ sudo apt-get update
  1. Install Docker Engine, containerd and Docker Compose.
 1
 sudo apt install docker-ce docker-ce-cli containerd.io docker-compose-plugin
  1. Verify that docker is installed successfully by running the hello-world image
 1
 sudo docker run hello-world

rpm series

In fact, to be honest, I personally don’t like this kind of distribution. Take CentOS as an example. The version above CentOS 7 can also be installed directly with yum.

Set up warehouse

The same is to set up a third-party repository.

However, you must first install yum-utils to use yum-config-manager .

 1
 sudo yum install -y yum-utils

Then set up the repository

 1 2 3
 sudo yum-config-manager \ --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo

Install

The same is to use the yum command to install docker packages and dependencies.

 1
 sudo yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin

A word on the Linux platform

The above methods are to install the latest version of docker on the Linux platform. If you need to install a specific version, you can refer to the official documentation of docker for operation.

Windows

On the Windows platform, you can directly install docker-desktop, which is also very simple, just download the installation package directly from the docker official documentation .

How can I play with docker?

There are so many things docker can do.

The most commonly used is to run applications in docker containers.

HelloWorld

For example, let’s run a Hello World

 1
 sudo docker run ubuntu /bin/echo "hello world"

As you can see, it outputs hello world at the end after outputting a series of characters

So let’s explain the meaning of the command

  • docker – run docker binaries, nothing to say about this
  • run – run the container
  • ubuntu – the name of the image to run
  • /bin/echo "hello world" – the command to execute inside the container
hint

If the following information appears, it may be because the relevant image was not downloaded when the container was started

 1 2 3
 Unable to find image 'ubuntu:latest' locally latest: Pulling from library/ubuntu e96e057aae67: Pull complete

By default, docker will automatically download, but it is best to get into the habit of downloading images before starting.

 1
 sudo docker pull ubuntu

interactive container

Of course, we can also create an interactive container, which means we can use bash to control it

 1
 sudo docker run -i -t ubuntu /bin/bash
Parameter meaning
  • -i : Interactive operation.
  • -t : Terminal.

Quoted from the rookie tutorial

In this way, after we create the container, our shell also becomes the shell in the container

We can perform some operation commands on it, just type a few.

And the commands we execute will not affect the main system

Then we can use the exit command to exit the system.

As a result, the container’s operating system exits, and the container stops running, because the container is not running in daemon mode.

Run the container in daemon mode

The next thing I want to say is why it is not finished after exiting the container shell with exit .

This time we open another container, but this time add a parameter -d

This parameter means to run in Daemon mode, so what does Daemon mean?

The answer obtained through the search engine is often what the system daemon Balabala means, in fact, it is similar to the meaning of running in the background.

Next we use this command to open a container

 1
 sudo docker run -i -t -d ubuntu /bin/bash

At this time, we found that we did not get a shell, but a string of strings.

Let’s try using docker’s ps command to see what containers are running:

 1
 sudo docker ps

We get this result

The picture may not be clear? Post it here

 1 2 3
 [weepingdogel@WeepingDogel-Arch ~]$ sudo docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2f4976200305 ubuntu "/bin/bash" About a minute ago Up About a minute funny_pare

Then I found that the container ID in the returned result is only the first part of the string returned above, which is often the container ID we will use

How can I control its shell?

Getting in touch with the new docker commands again

  • attach
  • exec

exec needs to add -i and -t parameters and commands, such as /bin/bash .

So the execution format is like this

 1
 sudo docker exec -it 容器ID 命令

Then we need to execute bash

 1
 sudo docker exec -it 2f4976200305 /bin/bash

Soon, we’re in the container’s shell.

We can use cat /etc/os-release to view system information.

We can clearly see that the above is returning Ubuntu and I am using Arch, so we can be sure that the contents of the container will not affect the operating system.

What? Not clear? Look more clearly then

 1 2 3 4 5 6 7 8 9 10 11 12
 PRETTY_NAME="Ubuntu 22.04.1 LTS" NAME="Ubuntu" VERSION_ID="22.04" VERSION="22.04.1 LTS (Jammy Jellyfish)" VERSION_CODENAME=jammy ID=ubuntu ID_LIKE=debian HOME_URL="https://www.ubuntu.com/" SUPPORT_URL="https://help.ubuntu.com/" BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" UBUNTU_CODENAME=jammy

Exit is still the same, you can use exit , but at this time exit just exits the bash, it does not close the container.

Execute docker ps we can see that it is still running.

So let’s try attach next

Its usage is

 1
 sudo docker attach 容器ID

So I need to execute

 1
 sudo docker attach 2f4976200305

This way we can also get a shell, but if we execute exit , the container will be stopped.

Come try it out?

Obviously, when exit is executed, the running container ID cannot be seen with the docker ps command, which means that the container is stopped.

If we need to start the container again, we can use the start or restart command to restart.

 1
 sudo docker restart 2f4976200305

At this point we can see it running again with docker ps

hint

Use the docker ps -a command to see all containers, whether they are running or not

 1
 sudo docker ps -a

delete container

What if these containers are no longer needed,

For example, if the game is broken, you need to delete it

Then use docker rm command

 1
 sudo docker rm 容器ID

You can delete it by adding the container ID, and you can delete multiple

 1
 sudo docker rm 6c8c8d9f5540 6c49bc1fdc49 eb71e810ee50 5a84d067d769 2addaf3666ef

Then when I use docker ps -a to view, I can’t see any container ID.

mirror

A prerequisite for a docker container to run is that it needs the corresponding image.

You can use docker images to view existing local images, and if you need other images, you can use docker pull to get them

 1
 sudo docker images

Let’s get the mirror of php

 1
 sudo docker pull php

Wait for their automatic download to complete and the mirrors are ready to use.

If you run the container without pulling the image beforehand, docker will temporarily pull the image while running the container.

After the download process is complete, let’s take a look at the existing mirrors

 1
 sudo docker images
 1 2 3 4
 REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest a8780b506fa4 7 days ago 77.8MB php latest 30e567f030d3 12 days ago 484MB httpd latest fe8735c23ec5 2 weeks ago 145MB
Description of each option:
  • REPOSITORY: Represents the repository source of the mirror

  • TAG: the tag of the mirror

  • IMAGE ID: Image ID

  • CREATED: Image creation time

  • SIZE: Image size

The same repository source can have multiple TAGs, representing different versions of the repository source. For example, in the ubuntu repository source, there are multiple different versions such as 15.10 and 14.04 . We use REPOSITORY:TAG to define different images.

Quoted from the rookie tutorial

delete mirror

Of course, unnecessary images can also be deleted.

 1
 sudo docker rmi 镜像ID

As shown in the figure, this will delete the unneeded images

dockerfile

What is dockerfile? Dockerfile is a text file used to build an image file. The file contains instructions and instructions, similar to some shell scripts (such as PKGBUILD )

And a simple Dockerfile looks like this

 1 2
 FROM nginx RUN echo 'Hello World!' > /usr/share/nginx/html/index.html 
Tips from the rookie tutorial
  • The images customized by FROM are all FROM-based images, and nginx here is the basic image required for customization. Subsequent operations are based on nginx.
  • RUN is used to execute the command line command that follows. There are two formats:

shell format:

 1 2
 RUN <命令行命令> # <命令行命令> 等同于,在终端操作的shell 命令。 

exec format:

 1 2 3
 RUN [ "可执行文件" , "参数1" , "参数2" ] # 例如: # RUN ["./test.php", "dev", "offline"] 等价于RUN ./test.php dev offline 

If you are familiar with Linux operation, it is very simple to get started, but it is worth noting this paragraph in the rookie tutorial:

Notice

Each time the instructions of the Dockerfile are executed, a new layer will be created on the docker. So too many meaningless layers will cause the image to expand too much. E.g:

 1 2 3 4
 FROM centos RUN yum -y install wget RUN wget -O redis.tar.gz "http://download.redis.io/releases/redis-5.0.3.tar.gz" RUN tar -xvf redis.tar.gz 

The above execution will create a 3-layer image. Can be simplified to the following format:

 1 2 3 4
 FROM centos RUN yum -y install wget \ && wget -O redis.tar.gz "http://download.redis.io/releases/redis-5.0.3.tar.gz" \ && tar -xvf redis.tar.gz 

That is to say, we should try our best to write parallel statements when writing command scripts in RUN.

A simple web server.

Now I want to try running a simple web page with docker.

Just run the login page that I had nothing to do before.

First we have to create a directory

 1
 mkdir webtest

First copy the static files in the front end

 1
 cp test/* webtest/ -rv

then go to that directory

 1
 cd webtest

check the file

 1
 ls -lh
 1 2 3 4 5
总计4.0K drwxr-xr-x 2 weepingdogel weepingdogel 23 11月10日21:30 css drwxr-xr-x 2 weepingdogel weepingdogel 6 11月10日21:30 img -rw-r--r-- 1 weepingdogel weepingdogel 1.4K 11月10日21:30 index.html drwxr-xr-x 2 weepingdogel weepingdogel 21 11月10日21:30 js

ok , now let’s write a dockerfile

 1 2 3 4
 FROM nginx COPY ./index.html /usr/share/nginx/html/index.html COPY ./css/style.css /usr/share/nginx/html/css/style.css COPY ./js/main.js /usr/share/nginx/html/js/main.js 
Instruction details
  • COPY

The copy command copies files or directories from the context directory to the specified path in the container.

Format:

 1 2
 COPY [ --chown = <user>:<group> ] <源路径1>... <目标路径> COPY [ --chown = <user>:<group> ] [ "<源路径1>" ,... "<目标路径>" ] 

[--chown=<user>:<group>] : Optional parameters, the user changes the owner and group of files copied to the container.

<源路径> : source file or source directory, here can be a wildcard expression, and its wildcard rule must satisfy Go’s filepath.Match rule. E.g:

 1 2
 COPY hom* /mydir/ COPY hom?.txt /mydir/ 

<目标路径> : The specified path in the container. The path does not need to be built in advance. If the path does not exist, it will be created automatically.

My idea is the same as the normal construction method. After installing nginx, copy the written static files to the web root directory, but using docker is much more efficient.

But if I didn’t use docker, I would spend at least half an hour more time to configure a virtual machine, configure the software source to install nginx or something, and it would take even more time, and now I only need to write a script to one-click Deploy, and save it as a mirror to share with others, once and for all~

Well, without further ado, let’s start building the image

Use the docker build command to build an image through the dockerfile file in the directory,

The attribute value of -t refers to <镜像名称:镜像标签>

 1
 sudo docker build -t webtest:latest .

Note that I also added a . at the end. This is called the path to the text above, and it also refers to a relative path.

What is a context path?
The context path means that when docker is building an image, sometimes it wants to use the local file (such as copying), after the docker build command knows this path, it will package all the content under the path.

Then we look at the mirror list

 1
 sudo docker images

Obviously, we can see the image we just created, the image ID is 9acd8c30bd5b .

Then deploy it to the container ~ use -p to specify the port binding <外部端口:内部端口>

 1
 sudo docker run -p 8080:80 -d 9acd8c30bd5b

Now we have mapped the container’s port 80 to the host’s port 8080~

Then visit our local IP + 8080 to access that page, I use 127.0.0.1:8080 to visit here

Successful visit!

In this way, the rapid deployment of nginx is complete!

Epilogue

After the initial study and experience of docker, I have also tasted its high efficiency and convenience, and I have gained a lot.

But it is still an introductory stage, and more advanced application methods are still waiting to be explored~

Eh? You ask me is it difficult? QwQ ~

People who are familiar with Linux should be able to play this in a few days, but it will take time to gain a deep understanding.

so be it

This article is transferred from: http://weepingdogel.github.io/posts/%E6%B5%85%E5%B0%9Ddocker/
This site is for inclusion only, and the copyright belongs to the original author.