Docker learning notes

Posted by saikiran on Thu, 27 Jan 2022 15:43:55 +0100

Docker

summary

Docker is an open source and lightweight container engine, which mainly runs on Linux and Windows and is used to create, manage and arrange containers.

Compared with VMware virtual machine, Docker uses container to host applications instead of operating system, so it has little overhead and high performance. However, Docker's isolation of applications is not as complete as virtual machines, so it can not completely replace VMware.

form

image

The docker image is equivalent to a template through which container services can be created, and multiple containers can be created

Federated file system

When downloading the image B, if there are some duplicate contents in the downloaded image A, then this part of the contents will be reused. The reused part is called the image layer of the image, and the downloaded part is the container layer

container

docker uses container technology to run a group of applications independently

Start stop delete basic command

Understood as a simple linux system

Warehouse

Public warehouse and private warehouse docker hub (foreign by default)

Alicloud has container servers (image acceleration)

Store image!

install

Uninstall old

yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine

Installing docker on linux

software package

sudo yum install -y yum-utils
//Set the image warehouse. Alicloud is foreign by default
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

Update package index

yum makecache fast

Install docker

sudo yum install docker-ce docker-ce-cli containerd.io

command

start-up

systemctl start dockers
systemctl start docker.service

View version

docker version

Run Hello world image

docker run centeros /bin/echo "Hello world"
# Docker with Ubuntu 15 10 image create a new container, then execute bin/echo "Hello world" in the container, and then output the result.

View mirror

docker images

uninstall

sudo yum remove docker-ce docker-ce-cli containerd.io

sudo rm -rf /var/lib/docker

sudo rm -rf /var/lib/containerd

Help command

Help documentation https://docs.docker.com/reference/

docker version  # Display docker version information
docker info  # docker system information includes the number of images and containers 
docker command --help #Help command

Mirror command

docker images view images on all local hosts

#explain
REPOSITORY Mirrored warehouse source
TAG   Mirrored label
IMAGE ID image id
CREATED  Creation time of image
SIZE  Mirror size
# Optional
-a --all # List all mirrors
-q --quiet # Show id ONLY

docker serach search image name (e.g. mysql)

--filter=STARS=3000 The mirror image found starts Greater than 3000
 example docker search mysql --filter=stars=5000

docker pull Download Image

docker pull Image name:edition
docker pull mysql Equivalent to
docker pull mysql docker.io/libray/mysql:latest

docker rmi delete image

docker rmi -f image id                    Delete container
docker rmi -f image id image id image id   Delete multiple containers
docker rmi -f $(docker images -aq)  Delete all containers

Container command

You cannot create a container until you have a mirror

Next centeros

docker pull centos

Create a new container and start it. The operation object is the image. After entering, you can modify the files in the image

docker run [Optional parameters] image

#parameter
-t  Specify a pseudo terminal or terminal in the new container.
-i  Allows you to enter the standard in the container (STDIN) Interact.
--name="Name" Container name
-d Background mode operation nohup
-it Run interactively
-p Specify the port of the container -p 8080:8080
-P Randomly assigned port
--restart alway  # always restart when the container exits on failure: restart when the container exits (the return value is non-zero). no: do not restart when the container exits
 -v Host Directory:Container directory  #
  30                   [OK]
# Start and enter the container
docker run -it centos /bin/bash
exit Will exit and stop the container

List all running containers

docker ps

docker ps #Currently running
-a        #Plus what history has run
-n=?      #Show recently run
-q        #Show container id only 

Exit container start container

exit # Stop and exit
Ctrl + P + Q #Quit without stopping
docker stop container id # Stop the container after exiting
docker start container id
docker restart container id
docker kill container id #Force

Delete container

docker rm container id               #Delete specified container
docker rm -f $(docker ps -aq) #Delete all containers 

Start container and stop container

docker start container id
docker restart container id
docker stop container id 
docker kill container id

Enter the running container

#Exit the current container
exit 
# Enter the container and start a new command line 
docker exec  -it container id bash
#Enter the running command line
docker attach container id bash 

The difference between docker run and docker exec

  • docker run creates a container based on the image, and then operates the image
  • docker exec is to enter a running container

Create a new image from the container

docker run -it -p xxx  #Start container
 Modify the contents of the container

Open a new window
docker commit -m="Information submitted at one time"  [Container to modify id] New image name  #Commit image
docker commit -a='yc9064' -m='docker New image commit test' 96dd74b37e87 mynginx:v1

docker images #View the replayed image

docker run -d -p 8080:80 --name mynginx01 --restart always -v /root/nginx/html:/usr/share/nginx/html  mynginx:v1
  • -a: the author of the submitted image;
  • -c: use Dockerfile instruction to create image;
  • -m: explanatory text at the time of submission;
  • -p: pause the container during commit.

Common other commands

Background start

docker run -d centos 
#discover problems
docker ps The discovery stopped
 A foreground process is necessary for background operation  docker If no application is found, it will stop automatically

Often read logs

example

#Execute loop script
docker run -d centos /bin/sh -c "while true;do echo hi;sleep 5;donre"

#View container id
docker ps

#View log of output
docker logs -tf --tail 100 container id

View process information in container

docker top container id

3. View the metadata of the container

docker inspect container id

Copy files from container to host

docker cp container id:The path to the destination host of the file path in the container

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xxSBlhvO-1640666584521)(.\img(.png)]

Alibaba cloud image acceleration

Log in to alicloud and find the container image service

Find the image acceleration address

sudo mkdir -p /etc/docker

sudo tee /etc/docker/daemon.json <<-'EOF'
{   
  "registry-mirrors": ["https://5gw6wzma.mirror.aliyuncs.com"]
}
EOF

sudo systemctl daemon-reload

sudo systemctl restart docker

Use mirror

Installing nginx

docker pull nginx
#View open port numbers
firewall-cmd --list-ports 
#Open 8080 port
firewall-cmd --zone=public --add-port=8080/tcp --permanent 
#restart
firewall-cmd --reload 
#-p expose the port (of the container) - d run in the background - name to name the container
#Run the nginx container named nginx01 and map the 8080 port of the machine to the 80 port of the container 
# --restart always restart the docker and start the container
[root@masterServr ~]# docker run -d -p 8080:80 --name nginx01 --restart always -v /root/nginx/html:/usr/share/nginx/html  nginx
WARNING: IPv4 forwarding is disabled. Networking will not work.
b435252b28d1b6a6bf944d470102371658744e10f948b6632249d3e59a0b9311

[root@masterServr ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                                   NAMES
b435252b28d1   nginx     "/docker-entrypoint...."   15 seconds ago   Up 14 seconds   0.0.0.0:3344->80/tcp, :::3344->80/tcp   nginx01
f67252424cc0   centos    "/bin/bash"              18 hours ago     Up 18 hours                                             silly_zhukovsky


Install tomcat

# --Delete the test when rm stops
docker run -it --rm tomcat:9.0

Open port number
docker pull tomcat:9.0

docker runn -d -p ...

Visit the url to get the tomcat 404 page

The webapp directory in the container was found to be empty

This indicates that the tomcat image is reduced

Reason: the default is the minimum image, and all unnecessary things are eliminated

Container data volume

Problem: if the data exists in the container, we delete the container and the data is deleted

Requirement: data can be persistent

Mount the directory in the container to the host

Summary: for container persistence and synchronization, directories between containers can also be shared

Command -v Host Directory: container directory

Example:

docker run -d -p 8080:80 --name nginx01 --restart always -v /root/nginx/html:/usr/share/nginx/html  nginx

Named and anonymous mount

docker  run ...  -v  [In container directory] ... # anonymous

docker  run ...  -v  [Take a name]:[In container directory]:[file right ro/rw] ... # Named ro is the read-only permission of container file. To change the text, you need to go to the host
docker volume ls # View all mounts
docker inspect [volumeName]

File synchronization between containers

Information transfer between containers, such as l data synchronization of mysq container

docker run -it --name docker01 xxx:1.0
#Bind dcoker02 to docker01 for data synchronization
docker run -it --name docker02 --volumes-from dcoker01 xxx:1.0


docker run -it --name docker01 mycentos:v1 bash
docker run -it --name docker02 --volumes-from docker01 mycentos:v1 bash

DockerFile

The build file used to build the docker image is a command script

Therefore, we can not only modify the container and commit to build a new image locally, but also build the image by docker build [dockerfile file]

DockerFile construction process

When we publish a project in the future, we need to write a dockerfile to mirror it

Basic knowledge:

1. Each reserved keyword (instruction) must be capitalized

2. Execute from top to bottom

3. # indicates a comment

4. Each instruction will create and submit a new image layer

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RPCpp8pD-1640666584523)(.\img].jpg)]

Detailed explanation of Dockerfile instruction

  • FROM

    Basic image, FROM centos

  • MAINTAINER

    Mark author and email FROM liuyinchuan yc906478@163.com

  • RUN

    This operation affects mirroring

    • RUN [command]

      Use / bin/sh in the shell to run command s, such as RUN echo 'the image of this container is built through dockerfile' > readme txt

    • RUN ['specify program', 'parameter 1', 'parameter 2']

      RUN["/bin/bash","-c","echo hello"]

  • CMD

    CMD is used to specify the command to be executed when the container is started. Each Dockerfile can only have one CMD command,

    After the image is built, if the running command is specified when the container starts, the command specified in CMD will be overwritten

    CMD ['specify program', 'parameter 1', 'parameter 2']

  • ENTRYPOINT

    Similar to CMD

    After the image is built, if the running command is specified when the container is started, it will be appended to the original instruction

  • EXPOSE

    When exposing the port configuration, you can also add - p [port number] when run ning

  • ADD

    Add the file to the image. If it is a compressed package, it will be decompressed

    ADD [source file path] [path in image]

  • COPY

    Similar to ADD, the file will not be decompressed

  • ENV

    Setting container environment variables

    ENV JAVA_HOME=/usr/local/jdk_1.8.201/

  • WORKDIR

    To specify the configuration working directory for the subsequent RUN CMD ENTRYPOINT, you can use multiple WORKDIR instructions. If the subsequent instructions use relative paths, the paths will be specified based on the previous commands.

    WORKDIR /path

FROM		#Basic image, everything starts from here
MAINTAINER	#Who wrote the image, name + email
RUN			#Commands to run during image construction
ADD			#Step, tomcat image, this tomcat compressed package! Add content
WORKDIR		#Mirrored working directory	
VOLUME		#Anonymous mounted directory
EXPOSE		#When exposing the port configuration, you can also add - p [port number] when run ning
CMD			#Specify the command to run when the container starts. Only the last one will take effect and can be replaced
ENTRYPOINT	#Specify the commands to be run when the container is started, and you can append commands
ONBUILD		#When an inherited Dockerfile is built, the ONBUILD instruction will be run
COPY 		#Similar to ADD, copy our files to the image

Example:

Create a dockerfile1

Upload jdk-8u281-linux-x64.0 tar. gz

vim dockerfile1

FROM centos                        # Using centos as the base image
MAINTAINER OBy yc906478@163.com

ENV MYPATH=/usr/local
WORKDIR $MYPATH

VOLUME ["volume01","volume02","volume03"]   #Anonymous mount directory 

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 80
CMD echo
CMD echo "---end---"
CMD /bin/bash
docker build -f dockerfile1 -t mycentos:v1 . #Use the dockerfile of the current directory to build the v1 version of mycentos
docker run -it my

Build image

After writing the dockerfile, you can build the image to the local

docker build -t nginx:v3 .
docker build -f dockerfileName -t /filepath .

Context path refers to the file (such as copy) that docker sometimes wants to use when building an image. After knowing this path, docker build command will package all the contents under the path.

actual combat

Centos

Create a file named Dockerfile so that it will be found when build ing without entering the file name

FROM centos:7                       
MAINTAINER OBy yc906478@163.com

ENV MYPATH=/usr/local
WORKDIR $MYPATH

VOLUME ["volume01","volume02","volume03"]

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 80
CMD echo "---end---"
CMD /bin/bash

Build:

docker build -f mydockerfile-centeros -t mycentos:0.1 

Tomcat

Dockfile

FROM centos
#author
MAINTAINER yc 906478612@qq.com
#Copy tomcat jdk to the image and unzip it
ADD apache-tomcat-8.5.73.tar.gz /usr/local/tomcat
ADD jdk-8u281-linux-x64.tar.gz /usr/local/jdk

RUN yum -y install vim
#Define login path during interaction
ENV MYPATH /usr/local
WORKDIR $MYPATH
#Configure jdk and tomcat environment variables
ENV JAVA_HOME /usr/local/jdk/jdk1.8.0_281
ENV CATALINA_HOME /usr/local/tomcat/apache-tomcat-8.5.73
ENV CATALINA_BASE /usr/local/tomcat/apache-tomcat-8.5.73
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
#Set exposed ports
EXPOSE 8080
#Run tomcat
CMD /usr/local/tomcat/apache-tomcat-8.5.73/bin/startup.sh && tail -f /usr/local/tomcat/apache-tomcat-8.5.73/logs/catalina.out

docker run -d -p 8080:8080 --name mytomcat -v /usr/local/tomcat/logs:/usr/local/tomcat/apache-tomcat-8.5.73/logs/ -v /usr/local/tomcat/webapps:/usr/local/tomcat/apache-tomcat-8.5.73/webapps/ diytomcat

Topics: Operation & Maintenance