docker learning notes

Posted by croakingtoad on Thu, 24 Feb 2022 09:30:51 +0100

I Download docker and install it

Docker Desktop official download address

1. Installing docker in CentOS 7

1. Use the official installation script to install automatically
curl -sSL https://get.daocloud.io/docker | sh

2. Install docker engine community

2.Win10 installation

Just keep clicking on the next step

If not, check to see if Hyper-V is installed
The latest device is turned on by default,

II Container use

1.docker view all commands

Use docker to view all the commands of docker

You can also use Docker (command) – help to have a deeper understanding of the use method of the specified Docker command and the commands you want to view in detail

2. Get image

#Obtaining the ubuntu system image can be changed to other images

docker pull ubuntu

3. View owned images

docker images
or
docker ps -a

View started images
docker ps

3. Start the image

## 1. Front Desk operation

docker run -it ubuntu /bin/bash
-i: Interactive operation.

-t: Terminal.

ubuntu: ubuntu Mirror image.

/bin/bash: After the image name is the command. Here we want to have an interactive Shell,So it uses /bin/bash
 Exit use    exit:

#Background operation - d specifies the operation mode of the container.

docker run -itd --name ubuntu-test ubuntu /bin/bash

4. Enter the container

#Not recommended. Exiting will close the container
docker attach 1e560fca3906(container id)

#It is recommended to exit from the container, which will not stop
docker exec -it 243c32535da7 /bin/bash

5. Container operation

#View all containers
docker images
#Start container
docker start container id Or container name
#View container log
docker logs container id Or container name
#Restart container
docker restart container id Or container name
#Stop container
docker stop  container id Or container name
#Delete container
docker rm -f 1e560fca3906

6. Export and import containers

#Export container
docker export 1e560fca3906(container id Or container name) > ubuntu.tar
#Import container snapshot
cat docker/ubuntu.tar | docker import - test/ubuntu:v1
 Or by specifying URL Or a directory to import
docker import http://example.com/exampleimage.tgz example/imagerepo

III Mirror use

1. List images

docker images

2. Find image

docker search Image name

3. Download a new image

docker pull ubuntu:13.10(Image name: version number)

4. Submit image

docker commit -m="has update" -a="nhooo" e218edb10161 nhooo/ubuntu:v2
 Description of each parameter:

-m: Description information submitted

-a: Specify mirror author

e218edb10161: container ID

nhooo/ubuntu:v2: Specifies the name of the target image to create

5. Build image

docker build (dockerfile (file)

6. Image renaming

docker rename Original container name new container name

4, Container connection

1. # create a container for python application

docker run -d -P training/webapp python app.py

#Use the - P parameter to create a container. Using docker ps, you can see that container port 5000 is bound to host port 32768
#-p ID to specify that the container port is bound to the host port.

#The difference between the two methods is:

#-P: the internal port of the container is randomly mapped to the high port of the host.

#-p: the internal port of the container is bound to the specified host port.

2. Use - p to bind to port 5000 and map to port 5000 of the host

docker run -d -p 5000:5000 training/webapp python app.py

3. Specify the network address bound by the container, such as binding 127.0.0.1

docker run -d -p 127.0.0.1:5001:5000 training/webapp python app.py

4. The default is to bind tcp ports. If you want to bind udp ports, you can add / udp after the ports.

docker run -d -p 127.0.0.1:5000:5000/udp training/webapp python app.py

5. Check the binding of ports

docker port  container id Or name

6.Docker container interconnection

7. Container naming

#Use the -- name identifier to name the container
docker run -d -P --name nhooo training/webapp python app.py

8. New network

docker network create -d bridge test-net
#-d: Parameter specifies the Docker network type, including bridge and overlay.
#The overlay network type is used for Swarm mode

9. Connect the container

Run a container and connect to the newly created test net network:

docker run -itd --name test1 --network test-net ubuntu /bin/bash

Open a new terminal, run another container and join the test net network:

docker run -itd --name test2 --network test-net ubuntu /bin/bash

Ping is used to prove that test1 container and test2 container have established an interconnection relationship. If there is no ping command in test1 and test2 containers, execute the following command in the container to install Ping

Command installation ping
apt-get update
apt install iputils-ping
#Enter container 1 and Ping container 2
ping test2

10. Configure DNS

The linux system is located in / etc / docker / daemon. Of the host computer Add the following content to the JSON file to set the DNS of all containers:
After configuration, you need to restart docker to take effect

{
  "dns" : [
    "114.114.114.114",
    "8.8.8.8"
  ]
}
#To check whether the DNS of the container is effective, you can use the following command, which will output the DNS information of the container
docker run -it --rm  ubuntu  cat etc/resolv.conf

11. Manually configured containers

docker run -it --rm -h host_ubuntu  --dns=114.114.114.114 --dns-search=test.com ubuntu
#Parameter Description:

#--rm: automatically clean up the file system inside the container when the container exits.

#-h HOSTNAME or -- hostname=HOSTNAME: set the host name of the container, which will be written to / etc/hostname and / etc/hosts in the container.

#--dns=IP_ADDRESS: add DNS server to / etc / resolv. Of the container Conf, let the container use this server to resolve all host names that are not in / etc/hosts.

#--DNS search = domain: set the search domain of the container. When the search domain is set to example.com, when searching for a host named host, DNS searches not only host, but also host example.com. 

V Warehouse management

Docker Hub
At present, Docker officially maintains a public warehouse Docker Hub.

Most of the requirements can be realized by directly downloading images in Docker Hub.
register
In https://hub.docker.com Register a Docker account for free.

1. Login and logout

The user name and password are required for login. After successful login, we can pull all the images under our account from the docker hub.

#Sign in
docker login
#sign out
docker logout

2. Pull the image

Example:
Search with ubuntu as the keyword

#Search image
docker search ubuntu
#Pull image
docker pull ubuntu

3. Push image

After logging in, users can push their own images to the Docker Hub through the docker push command.

docker tag ubuntu:18.04 username/ubuntu:18.04

Vi Docker Dockerfile

1. Use Dockerfile to customize the image

In an empty directory, create a new file named Dockerfile, and add the following contents to the file:

FROM nginx
RUN echo 'This is a locally built nginx image' > /usr/share/nginx/html/index.html

2. Function of from and RUN instructions

FROM: customized images are all FROM based images. Nginx here is the basic image required for customization. Subsequent operations are based on nginx.

RUN: used to execute the following command line commands.
shell format:

RUN <Command line command>
<Command line command> Equivalent to, operating at the terminal shell Command.

exec format:

RUN ["Executable file", "Parameter 1", "Parameter 2"]
For example:
RUN ["./test.php", "dev", "offline"] Equivalent to RUN ./test.php dev offline

Every time the Dockerfile instruction is executed, a new layer will be created on the docker. Therefore, too many meaningless layers will cause the image to expand too much

Example:

ROM centos
RUN yum 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 three-tier image. It can be simplified to the following format:

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

Connect the command with the & & symbol. After execution, only one layer of image will be created

3. Start building the image

#Build an nginx:v3 (image name: image label) through the Dockerfile in the directory
docker build -t nginx:v3 

COPY
Copy instruction, copy files or directories from the context directory to the specified path in the container.
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.

COPY [--chown=<user>:<group>] <Source path 1>...  <Target path>
COPY [--chown=<user>:<group>] ["<Source path 1>",...  "<Target path>"]

Refer to this tutorial for more commands

VII Docker Compose

Compose is a tool for defining and running multi container Docker applications. With compose, you can use the YML file to configure all the services required by your application. Then, with one command, you can create and start all services from the YML file configuration.

1. Use steps

Three steps for Compose:

Use Dockerfile to define the environment of the application.

Use docker compose YML defines the services that make up the application so that they can run together in an isolated environment.

Finally, execute the docker compose up command to start and run the entire application.

2.Compose installation

2.1Linux

On Linux, we can download its binary package from Github to use. The latest version address is: https://github.com/docker/compose/releases.

Run the following command to download the current stable version of Docker Compose:

$ sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

To install a different version of Compose, replace 1.24.1.

Apply executable permissions to binaries:

$ sudo chmod +x /usr/local/bin/docker-compose

To create a soft chain:

$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

Test for successful installation:

$ docker-compose --version
#Return information
#cker-compose version 1.24.1, build 4667896b

Note: for alpine, the following dependency packages are required: py pip, python dev, libffi dev, OpenSSL dev, gcc, libc dev, and make.

2.2windows PC

The Docker desktop version and Docker Toolbox of windows already include Compose and other Docker applications Therefore, Windows users do not need to install Compose separately.

3. Use Compose

1. Prepare

Create a test directory:

#mkdir composetest
#cd composetest
Create an app in the test directory Py, and copy and paste the following:
composetest/app.py file code

import time

import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)


def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)


@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

In this example, redis is the host name of the redis container on the application network, and the port used by the host is 6379.

In the composetest directory, create another one called requirements Txt, as follows:

flask
redis

2. Create Dockerfile file

In the composetest directory, create a Dockerfile named as follows:

FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]

Dockerfile content explanation:

FROM python:3.7-alpine: build the image from the Python 3.7 image.

WORKDIR /code: set the working directory to / code.

ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0

Set the environment variable used by the flash command.

Run APK add -- no cache gcc musl dev Linux headers: install gcc so that Python packages such as MarkupSafe and SQLAlchemy can be compiled and accelerated.

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

Copy requirements Txt and install Python dependencies.

COPY . .: Will Copy the current directory in the project to The working directory in the image.

CMD ["flash", "run]: the default execution command provided by the container is: Flash run.

3. Create docker compose yml

In the test directory, create a file named docker - compose YML and paste the following:

docker-compose.yml profile

# yaml configuration
version: '3'
services:
  web:
    build: .
    ports:
     - "5000:5000"
  redis:
    image: "redis:alpine"

The Compose file defines two services: web and redis.

Web: this web service uses the image built from the current directory of Dockerfile. It then binds the container and host to the exposed port 5000. This sample service uses the default port 5000 of the flash web server.

Redis: this redis service uses the public redis image of Docker Hub.

4. Use the Compose command to build and run your application

In the test directory, execute the following command to start the application:

docker-compose up

If you want to execute the service in the background, you can add the - d parameter:

docker-compose up -d

8, Docker Machine

Docker Machine is a tool that allows you to install docker on a virtual host, and you can use the Docker Machine command to manage the host.

Docker Machine can also centrally manage all docker hosts, such as quickly installing docker on 100 servers.

The virtual hosts managed by Docker Machine can be on-board or cloud providers, such as Alibaba cloud, Tencent cloud, AWS, or DigitalOcean.

You can check the host and the Docker daemon, and you can also use the command to restart the host and Docker.

1. Installation

You need to install Docker before installing Docker Machine.
Linux Installation command

base=https://github.com/docker/machine/releases/download/v0.16.0 &&
  curl -L $base/docker-machine-$(uname -s)-$(uname -m) >/tmp/docker-machine &&
  sudo mv /tmp/docker-machine /usr/local/bin/docker-machine &&
  chmod +x /usr/local/bin/docker-machine

macOS installation command

base=https://github.com/docker/machine/releases/download/v0.16.0 &&
  curl -L $base/docker-machine-$(uname -s)-$(uname -m) >/usr/local/bin/docker-machine &&
  chmod +x /usr/local/bin/docker-machine

Windows installation command
If you are a Windows platform, you can use Git BASH and enter the following command:

base=https://github.com/docker/machine/releases/download/v0.16.0 &&
  mkdir -p "$HOME/bin" &&
  curl -L $base/docker-machine-Windows-x86_64.exe > "$HOME/bin/docker-machine.exe" &&
  chmod +x "$HOME/bin/docker-machine.exe"

Check whether the installation is successful:

docker-machine version

#Return information
docker-machine version 0.16.0, build 9371605

2. Use

1. List available machines
You can see that there is only the default virtual machine here at present.

docker-machine ls

2. Create machine
Create a machine called test.

docker-machine create --driver virtualbox test

– driver: Specifies the type of driver used to create the machine. Here is the virtualbox.
3. View the ip address of the machine

docker-machine ip test

4. Stop the machine

docker-machine stop test

5. Start the machine

docker-machine start test

6. Enter the machine

docker-machine ssh test

Description of docker machine command parameters
config: view the connection information of Docker host in the current active state.

Create: creat es a Docker host

env: displays the environment variables required to connect to a host

inspect: output the detailed information of the specified Docker in json format

ip: get the address of the specified Docker host

Kill: directly kill the specified Docker host

ls: list all management hosts

provision: reconfigure the specified host

Regenerate certs: regenerate TLS information for a host

Restart: restart the specified host

rm: when a Docker host is deleted, the corresponding virtual machine will also be deleted

SSH: connect to the host through SSH and execute the command

scp: remote replication of data between Docker hosts and between Docker hosts and local hosts through scp

Mount: use SSHFS to mount or unmount directories from the computer

Start: start a specified Docker host. If the object is a virtual machine, the virtual machine will be started

Status: get the status of the specified Docker host (including: Running, Paused, Saved, Stopped, Stopping, Starting, error, etc.)

Stop: stop a specified Docker host

upgrade: update the Docker version of a specified host to the latest version

URL: get the listening URL of the specified Docker host

Version: displays the Docker Machine version or host Docker version

Help: displays help information

9, Install common images

1. Install CentOS

1. Find image
Access CentOS image library address: https://hub.docker.com/_/centos?tab=tags&page=1 .
2. Pull the CentOS image of the specified version

docker pull centos:centos7

3. View local image

docker images

4. Run the container, and you can enter the CentOS container through the exec command.

docker run -itd --name centos-test centos:centos7

5. Installation succeeded
You can view the operation information of the container through the docker ps command

2. Install MySQL

1. View available MySQL versions
Access MySQL image library address: https://hub.docker.com/_/mysql?tab=tags .

2. Pull MySQL image
Here we pull the latest version of the official image:

docker pull mysql:latest

3. View local mirror
Use the following command to check whether mysql is installed:

docker images

4. Run container
After installation, we can use the following command to run the mysql container:

docker run -itd --name mysql-test -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql

Parameter Description:

-p 3306:3306: map the 3306 port of the container service to the 3306 port of the host. The external host can directly access the MySQL service through the host ip:3306.

MYSQL_ROOT_PASSWORD=123456: set the password of the root user of MySQL service.
5. Installation succeeded
Check whether the installation is successful through the docker ps command:

#Enter container
docker exec -it mysql-test /bin/bash

#Login to mysql
mysql -h localhost -u root -p
 Enter after entering the password mysql

If you are connected to MySql message 2059, use the following command to reset the password

ALTER  USER  'root'  IDENTIFIED  WITH  mysql_native_password  BY  '1234567';

This machine can access MySQL service through root and password 123456.

3. Install Redis

1. View available Redis versions
Access Redis image library address: https://hub.docker.com/_/redis?tab=tags
2. Take the latest version of Redis image
Here we pull the latest version of the official image:

docker pull redis:latest

3. View local mirror
Use the following command to check whether redis is installed:

docker images

4. Run container
After installation, we can use the following command to run redis container:

 docker run -itd --name redis-test -p 6379:6379 redis

-p 6379:6379: map the 6379 port of the container service to the 6379 port of the host. External users can directly access Redis services through the host ip:6379
5. Installation succeeded
Finally, we can view the operation information of the container through the docker ps command

6. View redis
Then we test the use of redis service through redis cli connection.

#Enter container
docker exec -it redis-test /bin/bash
#View redis
edis-cli 

4. Install MongoDB

1. View available MongoDB versions
Access MongoDB image library address: https://hub.docker.com/_/mongo?tab=tags&page=1.
2. Take the latest version of MongoDB image
Here we pull the latest version of the official image:

docker pull mongo:latest

3. View local mirror
Use the following command to see if mongo is installed:

docker images

4. Run container
After installation, we can run the mongo container with the following command:

docker run -itd --name mongo -p 27017:27017 mongo --auth

-p 27017:27017: map the 27017 port of the container service to the 27017 port of the host. External users can directly access mongo's services through the host ip:27017.

– auth: a password is required to access the container service.

5. Installation succeeded
Finally, we can view the operation information of the container through the docker ps command

6. Configure mongodb
Use the following commands to add users and set passwords, and try to connect.

#Enter container
docker exec -it mongo mongo admin
# Create a user named admin with a password of 123456.
db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
# Try to connect using the user information created above.
db.auth('admin', '123456')

Learn from cainiaojc
See the connection for more details

Topics: Docker Container