DOCKER学习笔记

学习参考网站:http://www.dockone.io/article/8350

一、DOCKER概述

1.1 认识Docker

是一个应用容器引擎,采用沙箱机制相互之间不会有任何接口。

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 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.

 

Hypervisor :EXSI  Hyper-V   Xen-Server

 

 

1.2 为什么用Docker

ü Docker可以容开发者打包他们的应用程序到一个可移植的容器中,可以发布到任何Linux机器上,便可以实现虚拟化;

ü 提高资源利用率,提高了服务的虚拟化;

ü 持续的交付和部署;

ü 更轻松的迁移。

Docker provides the ability to package and run an application in a loosely(轻易的) isolated (隔离的)environment called a container. The isolation隔离的 and security (安全的)allow you to run many containers simultaneously(同时的) on a given host. Containers are lightweight(轻量) and contain everything needed to run the application, so you do not need to rely on what is currently installed on the host. You can easily share containers while you work, and be sure that everyone you share with gets the same container that works in the same way.

Docker provides tooling and a platform to manage the lifecycle of your containers:

  • Develop your application and its supporting components组件 using containers.
  • The container becomes the unit for distributing and testing your application.
  • When you’re ready, deploy部署 your application into your production environment, as a container or an orchestrated安排 service. This works the same whether your production environment is a local data center, a cloud provider, or a hybrid 混合of the two.

1.3 Docker的应用场景

² Web应用的自动化打包和发布;

² 自动化测试和持续集成、发布;

² 在服务型环境中调整数据库或者后台应用;

² 云计算+大数据时代

        IaasInfrastructure-as-a-Service)基础设施即服务

        PaasPlatform-as-a-Service)平台即服务

        SaasSoftware-as-a-Service)软件即服务

Fast, consistent一致的 delivery传递 of your applications

Docker streamlines简化 the development lifecycle by allowing developers to work in standardized environments using local containers which provide your applications and services. Containers are great for continuous integration结合 and continuous持续的 delivery 传递(CI/CD) workflows工作流程.

Consider the following example scenario:

  • Your developers write code locally and share their work with their colleagues同事 using Docker containers.
  • They use Docker to push their applications into a test environment and execute automated自动化的 and manual tests.
  • When developers find bugs, they can fix处理 them in the development environment and redeploy them to the test environment for testing and validation.
  • When testing is complete, getting the fix to the customer is as simple as pushing the updated image to the production environment.

 

1.4 Docker和虚拟机总结

实现的原理技术不同;

使用资源方面不同;

应用场景不同;

Responsive应答的 deployment and scaling缩小

Docker’s container-based platform allows for highly portable轻便的 workloads. Docker containers can run on a developer’s local laptop, on physical or virtual machines in a data center, on cloud providers, or in a mixture of environments.

Docker’s portability轻便的 and lightweight nature also make it easy to dynamically manage workloads, scaling up 按比例缩放or tearing down拆卸 applications and services as business needs dictate, in near real time.

Running more workloads on the same hardware

Docker is lightweight and fast. It provides a viable, cost-effective alternative备选的 to hypervisor-based virtual machines, so you can use more of your compute capacity容量 to achieve your business goals. Docker is perfect for high density密度 environments and for small and medium deployments where you need to do more with fewer少量的 resources资源.

 

1.5 Docker总结

一致的运行环境,隔离性,弹性伸缩,快速扩展,方便迁移,持续的交付和部署。

Docker架构Docker architecture

2.1 架构简介

Docker uses a client-server architecture. The Docker client talks to the Docker daemon, which does the heavy重的 lifting of building, running, and distributing your Docker containers. The Docker client and daemon can run on the same system, or you can connect a Docker client to a remote Docker daemon. The Docker client and daemon communicate using a REST API, over UNIX sockets or a network interface. Another Docker client is Docker Compose, that lets you work with applications consisting of a set of containers.

 

 

2.2DOCKER Daemon引擎

The Docker daemon

The Docker daemon (dockerd) listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services.

 

 

2.2The Docker client

The Docker client (docker) is the primary way that many Docker users interact交互 with Docker. When you use commands such as docker run, the client sends these commands to dockerd, which carries运输传输 them out. The docker command uses the Docker API. The Docker client can communicate with more than one daemon.

2.3 Docker Desktop

Docker Desktop is an easy-to-install application for your Mac or Windows environment that enables you to build and share containerized容器化 applications and microservices微服务. Docker Desktop includes the Docker daemon (dockerd), the Docker client (docker), Docker Compose, Docker Content Trust内容信任, Kubernetes, and Credential凭证 Helper. For more information, see Docker Desktop.

2.4 Docker registries镜像仓库

A Docker registry stores Docker images. Docker Hub is a public registry that anyone can use, and Docker is configured配置 to look for寻找 images on Docker Hub by default. You can even run your own private registry.

When you use the docker pull or docker run commands, the required images are pulled from your configured registry. When you use the docker push command, your image is pushed to your configured registry.

 

2.5 Docker objects

When you use Docker, you are creating and using images, containers, networks, volumes, plugins外挂, and other objects. This section部分 is a brief简介的 overview概述 of some of those objects.

2.6 Images

An image is a read-only template模版 with instructiOften, an image is based on another image, with some additional额外的 customization定制的. For ons for creating a Docker container. example, you may build an image which is based on the ubuntu image, but installs the Apache web server and your application, as well as the configuration配置 details needed to make your application run.

You might create your own images or you might only use those created by others and published in a registry. To build your own image, you create a Dockerfile with a simple syntax for defining the steps步骤 needed to create the image and run it. Each instruction指导 in a Dockerfile creates a layer in the image. When you change the Dockerfile and rebuild the image, only those layers which have changed are rebuilt. This is part of what makes images so lightweight, small, and fast, when compared to other virtualization technologies.

2.7 Containers

A container is a runnable instance of an image. You can create, start, stop, move, or delete a container using the Docker API or CLI. You can connect a container to one or more networks, attach附上 storage to it, or even create a new image based on its current state.

By default, a container is relatively相对的 well isolated隔离的 from other containers and its host machine. You can control how isolated a container’s network, storage, or other underlying潜在的 subsystems子系统 are from other containers or from the host machine.

A container is defined by its image as well as any configuration配置 options you provide to it when you create or start it. When a container is removed, any changes to its state that are not stored in persistent持续的 storage disappear消失.

三、安装DOCKER 

Install Docker Engine on CentOS   https://docs.docker.com/engine/install/centos/

Prerequisites前提条件

OS requirements

To install Docker Engine, you need a maintained version of CentOS 7 or 8. Archived versions存档版本 aren’t supported or tested.

The centos-extras repository must be enabled. This repository is enabled by default, but if you have disabled it, you need to re-enable it.

The overlay2 storage driver is recommended推荐.

3.1安装前的准备 

卸载旧版本 Uninstall old versions

Older versions of Docker were called docker or docker-engine. If these are installed, uninstall them, along with associated联合 dependencies关联的依赖关系.

执行卸载命令:

 sudo yum remove docker \

                  docker-client \

                  docker-client-latest \

                  docker-common \

                  docker-latest \

                  docker-latest-logrotate \

                  docker-logrotate \

                  docker-engine

It’s OK if yum reports that none of these packages are installed.

The contents of /var/lib/docker/, including images, containers, volumes, and networks, are preserved. The Docker Engine package is now called docker-ce.

3.2安装开始

Installation methods

You can install Docker Engine in different ways, depending on your needs:

    Most users set up Dockers repositories and install from them, for ease of installation and upgrade提升 tasks. This is the recommended approach推荐的方式.

    Some users download the RPM package and install it manually手动的 and manage upgrades completely完全的 manually. This is useful in situations such as installing Docker on air-gapped systems with no access to the internet.

In testing and development environments, some users choose to use automated 自动的convenience 方便的scripts to install Docker.

 

方法一:使用仓库安装

 

Install using the repositoryBefore you install Docker Engine for the first time on a new host machine, you need to set up the Docker repository. Afterward, you can install and update Docker from the repository.

Set up the repository

1Install the yum-utils package (which provides the yum-config-manager utility) and set up the stable repository.

yum install -y yum-utils

添加软件源信息:

yum-config-manager     --add-repo     https://download.docker.com/linux/centos/docker-ce.repo

也可以添加阿里云的

yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

 

  1. 更新yum缓存

[root@localhost ~]# yum makecache fast

已加载插件:fastestmirror, langpacks

Loading mirror speeds from cached hostfile

dock                                                                                 | 3.6 kB  00:00:00     

docker-ce-nightly                                                                    | 3.5 kB  00:00:00     

docker-ce-stable                                                                     | 3.5 kB  00:00:00     

(1/4): docker-ce-stable/7/x86_64/updateinfo                                          |   55 B  00:00:01     

(2/4): docker-ce-nightly/7/x86_64/updateinfo                                         |   55 B  00:00:01     

(3/4): docker-ce-stable/7/x86_64/primary_db                                          |  70 kB  00:00:01     

(4/4): docker-ce-nightly/7/x86_64/primary_db                                         | 171 kB  00:00:02     

元数据缓存已建立

  1. 安装docker-CE

Install Docker Engine

 

Install the latest version of Docker Engine and containerd, or go to the next step to install a specific version:

出现报错:

 

解决方法:

[root@localhost ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

 

安装完成后继续执行:

[root@localhost ~]# yum install docker-ce docker-ce-cli containerd.io

 

安装成功!

This command installs Docker, but it doesn’t start Docker. It also creates a docker group, however, it doesn’t add any users to the group by default.

 

4.启动DOCKER  Start Docker.

[root@localhost ~]# systemctl start docker

查看版本:

[root@localhost ~]# docker version

Client: Docker Engine - Community

 Version:           20.10.12

 API version:       1.41

 Go version:        go1.16.12

 Git commit:        e91ed57

 Built:             Mon Dec 13 11:45:41 2021

 OS/Arch:           linux/amd64

 Context:           default

 Experimental:      true

 

Server: Docker Engine - Community

 Engine:

  Version:          20.10.12

  API version:      1.41 (minimum version 1.12)

  Go version:       go1.16.12

  Git commit:       459d0df

  Built:            Mon Dec 13 11:44:05 2021

  OS/Arch:          linux/amd64

  Experimental:     false

 containerd:

  Version:          1.4.12

  GitCommit:        7b11cfaabd73bb80907dd23182b9347b4245eb5d

 runc:

  Version:          1.0.2

  GitCommit:        v1.0.2-0-g52b36a2

 docker-init:

  Version:          0.19.0

  GitCommit:        de40ad0

 

Verify that Docker Engine is installed correctly by running the hello-world image.

 

# docker run hello-world

 

方法二:使用安装包安装  Install Docker Engine from binaries

https://docs.docker.com/engine/install/binaries/

 

 

1、下载安装包

Download the static binary archive. Go to https://download.docker.com/linux/static/stable/, choose your hardware platform, and download the .tgz file relating to the version of Docker Engine you want to install.

 

  1. Extract the archive using the tar utility. The dockerd and docker binaries are extracted.

 

[root@mysql docker]# tar -zxvf docker-19.03.15.tgz

 

  1. Optional: Move the binaries to a directory on your executable path, such as /usr/bin/. If you skip this step, you must provide the path to the executable when you invoke docker or dockerd commands.

 

[root@mysql docker]# cp docker/* /usr/bin/

 

 

  1. docker注册为service

 

vi docker.service

[Unit]

Description=Docker Application Container Engine

Documentation=https://docs.docker.com

After=network-online.target firewalld.service

Wants=network-online.target

  

[Service]

Type=notify

# the default is not to use systemd for cgroups because the delegate issues still

# exists and systemd currently does not support the cgroup feature set required

# for containers run by docker

ExecStart=/usr/bin/dockerd --selinux-enabled=false --insecure-registry=127.0.0.1

ExecReload=/bin/kill -s HUP $MAINPID

# Having non-zero Limit*s causes performance problems due to accounting overhead

# in the kernel. We recommend using cgroups to do container-local accounting.

LimitNOFILE=infinity

LimitNPROC=infinity

LimitCORE=infinity

# Uncomment TasksMax if your systemd version supports it.

# Only systemd 226 and above support this version.

#TasksMax=infinity

TimeoutStartSec=0

# set delegate yes so that systemd does not reset the cgroups of docker containers

Delegate=yes

# kill only the docker process, not all processes in the cgroup

KillMode=process

# restart the docker process if it exits prematurely

Restart=on-failure

StartLimitBurst=3

StartLimitInterval=60s

  

[Install]

WantedBy=multi-user.target

 

将编辑好的docker.service  复制到 /etc/systemd/system/

[root@mysql docker]# cp docker.service  /etc/systemd/system/

 

  1. 添加执行权限

[root@mysql docker]# chmod +x /etc/systemd/system/docker.service

 

  1. 重新加载配置文件

 

[root@mysql docker]# systemctl start docker.service

 

  1. 启动docker

 

[root@mysql docker]# systemctl start docker

 

  1. 设置开机启动docker

 

[root@mysql docker]# systemctl enable docker.service

四、DOCKER镜像

4.1列出镜像

[root@localhost docker]# docker images

REPOSITORY    TAG       IMAGE ID       CREATED        SIZE

hello-world   latest    feb5d9fea6a5   3 months ago   13.3kB

4.2获取镜像

Docker  pull  images  不加参数就是默认从官方下载

docker  pull   tomcate

docker  pull   tomcate:8

 

[root@localhost ~]# docker pull nginx

Using default tag: latest

latest: Pulling from library/nginx

a2abf6c4d29d: Pull complete

a9edb18cadd1: Pull complete

589b7251471a: Pull complete

186b1aaa4aa6: Pull complete

b4df32aa5a72: Pull complete

a0bcbecc962e: Pull complete

Digest: sha256:0d17b565c37bcbd895e9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31

Status: Downloaded newer image for nginx:latest

docker.io/library/nginx:latest

 

4.3删除DOCKER镜像

docker  rmi 镜像名称或者id

4.4 保存镜像

1.将本地仓库的镜像保存到指定目录:

docker  save  -o  镜像名称> 保存目录

  1. 将本地目录的镜像导入到仓库

docker  load  -i  tomcat.tar

五、DOCKER容器

what is a container? Simply put, a container is a sandboxed process on your machine that is isolated from all other processes on the host machine. That isolation leverages kernel namespaces and cgroups, features that have been in Linux for a long time. Docker has worked to make these capabilities approachable and easy to use. To summarize, a container:

  • is a runnable instance of an image. You can create, start, stop, move, or delete a container using the DockerAPI or CLI.
  • can be run on local machines, virtual machines or deployed to the cloud.
  • is portable (can be run on any OS)
  • Containers are isolated from each other and run their own software, binaries, and configurations.

Docker run reference参考

Docker runs processes in isolated 隔离的containers. A container is a process which runs on a host. The host may be local or remote. When an operator executes docker run, the container process that runs is isolated in that it has its own file system, its own networking, and its own isolated process tree separate from the host.

This page details how to use the docker run command to define the container’s resources at runtime.

 

General form大概形式

The basic docker run command takes this form:

$ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

The docker run command must specify 指定an IMAGE to derive获得 the container from. An image developer can define image defaults related to:

  • detached or foreground running决定容器的运行方式,前台执行还是后台执行
  • container identification 容器的分辨
  • network settings  网络设置
  • runtime constraints on CPU and memory 内存CPU的运行参数

5.1查看容器

https://docs.docker.com/engine/reference/commandline/container_run/

docker  ps

docker  ps  -a

5.2启动容器

Docker runs processes in isolated containers. A container is a process which runs on a host. The host may be local or remote. When an operator executes docker run, the container process that runs is isolated in that it has its own file system, its own networking, and its own isolated process tree separate from the host.

This page details how to use the docker run command to define the container’s resources at runtime.

The docker run command must specify指定 an IMAGE to derive提取 the container from. An image developer can define image defaults related to:

  • Detached分离 or foreground强调 running

当要启动一个docker容器时,首先必须决定是以detached模式在后台运行容器还是以默认的foreground模式运行:

-d=false: Detached mode: Run container in the background, print new container id

  • container identification鉴别
  • network settings
  • runtime constraints on CPU and memory

With the docker run [OPTIONS] an operator can add to or override覆盖 the image defaults set by a developer开发者. And, additionally此外, operators操作者 can override nearly all the defaults set by the Docker runtime itself. The operator’s ability to override image and Docker runtime defaults is why run has more options than any other docker command.

 

Operator exclusive独有的 options

Only the operator (the person executing docker run) can set the following options.

 

    Detached vs foreground

        Detached (-d)

        Foreground

    Container identification

        Name (--name)

        PID equivalent

    IPC settings (--ipc)

    Network settings

    Restart policies (--restart)

    Clean up (--rm)

    Runtime constraints on resources

    Runtime privilege and Linux capabilities

 

Detached vs foreground

When starting a Docker container, you must first decide if you want to run the container in the background in a “detached” mode or in the default foreground mode:

-d=false: Detached mode: Run container in the background, print new container id

Detached (-d)

To start a container in detached mode, you use -d=true or just -d option. By design, containers started in detached mode exit when the root process used to run the container exits, unless you also specify the --rm option. If you use -d with --rm, the container is removed when it exits or when the daemon exits, whichever happens first.

Do not pass a service x start command to a detached container. For example, this command attempts to start the nginx service.

Foreground

In foreground mode (the default when -d is not specified), docker run can start the process in the container and attach the console to the process’s standard input, output, and standard error. It can even pretend to be a TTY (this is what most command line executables expect) and pass along signals. All of that is configurable:

Container identification

Name (--name)

The operator can identify a container in three ways:

The UUID identifiers come from the Docker daemon. If you do not assign a container name with the --name option, then the daemon generates a random string name for you. Defining a name can be a handy方便的 way to add meaning to a container. If you specify a name, you can use it when referencing the container within a Docker network. This works for both background and foreground Docker containers.

PID equivalent

Finally, to help with automation, you can have Docker write the container ID out to a file of your choosing. This is similar to how some programs might write out their process ID to a file (you’ve seen them as PID files):

docker   run  常用的参数

      -d  在后台运行容器   

      --name  取名称

      -p   宿主机访问端口号:容器内部的端口号

 

[root@localhost ~]# docker run -d --name nginx21 -p 10080:80 nginx

a25008f7395b08e2bd79789900b9e894d15f0f7709906b9b9a3b65aaa91da20b

 

[root@localhost ~]# docker ps

CONTAINER ID   IMAGE     COMMAND                  CREATED              STATUS              PORTS                                     NAMES

a25008f7395b   nginx     "/docker-entrypoint."   About a minute ago   Up About a minute   0.0.0.0:10080->80/tcp, :::10080->80/tcp   nginx21

 

 

如果访问不通,肯能是防火墙的问题,给防火墙添加端口,

 

5.3 停止容器

[root@localhost ~]# docker stop 3248b3b7178f

3248b3b7178f

 

[root@localhost ~]# docker stop nginx-10080

nginx-10080

 

停止所有容器:

[root@localhost ~]# docker stop $(docker ps -a -q)

8d88f2a607ba

3248b3b7178f

 

 -q, --quiet           Only display container IDs

5.4 运行容器

[root@localhost ~]# docker start 8d88f2a607ba

8d88f2a607ba

5.5 删除容器

[root@localhost ~]# docker rm 8d88f2a607ba

8d88f2a607ba

 

5.6容器加端口

[root@localhost ~]# docker run -d --name nginx-10080 -p 10080:80 nginx

10080是外部访问端口就是主机的端口,80是内部端口,容器的端口

 

5.7进入容器

[root@localhost ~]# docker exec -it 33483b1dad16 /bin/bash

5.8宿主机和容器之间交换文件

 

docker容器中的文件拷贝出来

[root@localhost ~]# docker cp tomcat8:/usr/local/tomcat/webapps/ROOT/index.html /root

将文件拷贝到docker中:

[root@localhost ~]# docker cp index.html tomcat8:/usr/local/tomcat/webapps/ROOT/index.html

 

5.9查看docker日志

 

The docker logs command batch-retrieves logs present at the time of execution

 

[root@localhost ~]# docker logs 95d68fbba041

[root@localhost ~]# docker logs --tail=20 95d68fbba041

[root@localhost ~]# docker logs -f -t --since='2022-03-17' 95d68fbba041

六、docker数据卷

6.1docker  volume  create

Creates a new volume that containers can consume and store data in. If a name is not specified, Docker generates a random name.

 

docker run -d --name=tomcat8081 -p 8081:8080 -v /root/docker-volume:/usr/local/tomcat/webapps tomcat:8

docker run -d --name=tomcat8082 -p 8082:8080 -v /root/docker-volume:/usr/local/tomcat/webapps tomcat:8

 

 

多个容器可以共享一个数据卷。

对数据卷的更新立马生效;

数据卷更新不会影响镜像。

七.Docker安装软件

7.1安装nginx

下载镜像:

[root@localhost exam]# docker pull nginx

启动容器:

[root@localhost exam]# docker run -d --name=nginx80 -p 80:80 nginx

访问:

http://192.168.1.880

 

 

https://www.bilibili.com/video/BV1ug411j71W?p=20&spm_id_from=pageDriver

 

7.2安装mysql

1、下载镜像

[root@localhost exam]# docker pull mysql:5.7

2、启动容器

[root@localhost exam]# docker run -d --name mysql5.7 -p 3306:3306 -e MYSQL_ROOT_PASSWORD='mysql' mysql:5.7

609d20e40b5dc712e6f82eddff1b3523be1c5a717d7ce4f44eca953a73029686

3、进入容器:

[root@localhost exam]# docker exec -it 609d20e40b5d /bin/bash

4、进入数据库

root@609d20e40b5d:/# mysql -uroot -pmysql

5、授权其他主机登陆

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'mysql' WITH GRANT OPTION;

6、刷新权限

mysql> flush privileges;

7、远程访问

使用navcate访问mysql

八、DOCKER定制镜像

Dockerfile reference

Docker can build images automatically by reading the instructions(操作指南) from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble(收集) an image. Using docker build users can create an automated(自动的) build that executes several command-line instructions in succession.

This page describes the commands you can use in a Dockerfile. When you are done reading this page, refer to the Dockerfile Best Practices for a tip-oriented guide.

 

7.1常用命令

1FROM

The FROM instruction initializes a new build stage and sets the Base Image for subsequent随后的 instructions操作. As such, a valid有效的 Dockerfile must start with a FROM instruction. The image can be any valid image – it is especially easy to start by pulling an image from the Public Repositories.

 

2、ENV

docker容器设置环境变量,可以使用docker inspect查看,可以使用docker run --env <key><value>来修改环境变量。

The ENV instruction命令 sets the environment variable <key> to the value <value>. This value will be in the environment for all subsequent instructions in the build stage and can be replaced inline in many as well. The value will be interpreted for other environment variables, so quote characters will be removed if they are not escaped. Like command line parsing分析, quotes and backslashes can be used to include spaces within values.

Example:

ENV MY_NAME="John Doe"ENV MY_DOG=Rex\ The\ DogENV MY_CAT=fluffy

 

3MAINTAINER

添加标签,可以用label代替。

The MAINTAINER instruction sets the Author field of the generated发生的 images. The LABEL instruction is a much more flexible version of this and you should use it instead替代, as it enables setting any metadata you require, and can be viewed easily, for example with docker inspect. To set a label corresponding 一致to the MAINTAINER field you could use:

LABEL org.opencontainers.image.authors="SvenDowideit@home.org.au"

This will then be visible可见的 from docker inspect with the other labels.

3、WORKDIR

目录的切换工作。

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

The WORKDIR instruction can be used multiple times in a Dockerfile. If a relative path is provided, it will be relative to the path of the previous WORKDIR instruction. For example:

WORKDIR /aWORKDIR bWORKDIR cRUN pwd

The output of the final pwd command in this Dockerfile would be /a/b/c.

4、RUN

用来执行命令。

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

RUN命令在一层最开始执行命令并且提交结果,执行完成的结果用来Dockerfile中执行下一步的操作。

Layering RUN instructions and generating产生 commits conforms to the core concepts概念 of Docker where commits are cheap and containers can be created from any point in an image’s history, much like source control.

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain the specified指定的 shell executable.

The default shell for the shell form can be changed using the SHELL command.

In the shell form you can use a \ (backslash) to continue a single RUN instruction onto the next line. For example, consider these two lines:

5、EXPOSE

为容器打开指定要监听的端口,镜像内部的端口号。

The EXPOSE instruction informs告诉 Docker that the container listens on the specified network ports at runtime. You can specify指定 whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.

The EXPOSE instruction does not actually publish公开 the port. It functions功能 as a type of documentation记录 between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to high-order ports.

By default, EXPOSE assumes TCP. You can also specify UDP:

EXPOSE 80/udp

To expose on both TCP and UDP, include two lines:

EXPOSE 80/tcpEXPOSE 80/udp

In this case, if you use -P with docker run, the port will be exposed once for TCP and once for UDP. Remember that -P uses an ephemeral high-ordered host port on the host, so the port will not be the same for TCP and UDP.

Regardless不管怎样 of the EXPOSE settings, you can override them at runtime by using the -p flag. For example

 docker run -p 80:80/tcp -p 80:80/udp ...

To set up port redirection on the host system, see using the -P flag. The docker network command supports creating networks for communication among containers without the need to expose or publish specific ports, because the containers connected to the network can communicate with each other over any port. For detailed information, see the overview of this feature.

6、Copy

The COPY instruction copies new files or directories from <src> and adds them to the filesystem of the container at the path <dest>.

7、Add

The ADD instruction copies new files, directories or remote file URLs from <src> and adds them to the filesystem of the image at the path <dest>.

7.2编写dockerfile案例一

1.[root@localhost ~]# mkdir dockerdome

2root@localhost ~]# cd dockerdome/

3[root@localhost dockerdome]# vi dockerfile

FROM tomcat:8

RUN mkdir -p /usr/local/tomcat/webapps/ROOT/

RUN echo 'hello docker'>/usr/local/tomcat/webapps/ROOT/index.html

RUN  mkdir -p /usr/local/tomcat/webapps/

4[root@localhost dockerdome]# docker build -t demo1 .

Sending build context to Docker daemon  2.048kB

Step 1/4 : FROM tomcat:8

 ---> 1ff5878108be

Step 2/4 : RUN mkdir -p /usr/local/tomcat/webapps/ROOT/

 ---> Running in 6dedf4b32dc3

Removing intermediate container 6dedf4b32dc3

 ---> 4d84448f2793

Step 3/4 : RUN echo 'hello docker'>/usr/local/tomcat/webapps/ROOT/index.html

 ---> Running in 5cf5f513df27

Removing intermediate container 5cf5f513df27

 ---> 78f2926b67f1

Step 4/4 : WORKDIR /usr/local/tomcat/webapps/

 ---> Running in 23c3bfae22e7

Removing intermediate container 23c3bfae22e7

 ---> 7e35138ad745

Successfully built 7e35138ad745

Successfully tagged demo1:latest

5、查看镜像

[root@localhost dockerdome]# docker images

REPOSITORY    TAG       IMAGE ID       CREATED          SIZE

demo1         latest    7e35138ad745   55 seconds ago   679MB

6、启动镜像

 [root@localhost dockerdome]# docker run -d --name=demo1 -p 8085:8080 demo1

5b56b43bd7790557a3549b88165b5457f7c5b907a9e605f89420b86baf144ad6

7、访问页面验证

http://192.168.1.8:8085/index.html

7.3编写dockerifle案例二

1、编写dockerfile

Vi  dockerfile

FROM tomcat

WORKDIR /usr/local/tomcat/webapps/

RUN mkdir ROOT

COPY 1.jpb /usr/local/tomcat/webapps/ROOT/

2、构建镜像

[root@localhost dockerdome2]# docker build -t demo2 .

Sending build context to Docker daemon  2.134MB

Step 1/4 : FROM tomcat

 ---> 7a287e4562ea

Step 2/4 : WORKDIR /usr/local/tomcat/webapps/

 ---> Running in 56faf5f6181b

Removing intermediate container 56faf5f6181b

 ---> 15699a2e6a0a

Step 3/4 : RUN mkdir ROOT

 ---> Running in f76c56eb77f9

Removing intermediate container f76c56eb77f9

 ---> f615ab7b3876

Step 4/4 : COPY 1.JPG /usr/local/tomcat/webapps/ROOT/

 ---> bca42dfa782b

Successfully built bca42dfa782b

Successfully tagged demo2:latest

3、运行

[root@localhost dockerdome2]# docker run -d --name=demo2 -p 8086:8080 demo2

 

7.3编写dockerfile案例三

1、编写dockerfile文件

FROM tomcat

RUN mkdir -p /usr/local/tomcat/webapps/ROOT/

WORKDIR /usr/local/tomcat/webapps/ROOT

RUN rm -rf *

COPY in.tar.gz /usr/local/tomcat/webapps/ROOT/

RUN tar -zxvf in.tar.gz  -C /usr/local/tomcat/webapps/ROOT/

RUN rm -rf in.tar.gz

WORKDIR /usr/local/tomcat

2、创建镜像

[root@localhost dockerdome3]# docker build -t demo4 .

Sending build context to Docker daemon  3.072kB

Step 1/8 : FROM tomcat

 ---> 7a287e4562ea

Step 2/8 : RUN mkdir -p /usr/local/tomcat/webapps/ROOT/

 ---> Using cache

 ---> 817c7b76ca1e

Step 3/8 : WORKDIR /usr/local/tomcat/webapps/ROOT

 ---> Using cache

 ---> 001d0adef7e0

Step 4/8 : RUN rm -rf *

 ---> Using cache

 ---> 113a0bb0e830

Step 5/8 : COPY in.tar.gz /usr/local/tomcat/webapps/ROOT/

 ---> Using cache

 ---> 92c65d5d99b2

Step 6/8 : RUN tar -zxvf in.tar.gz  -C /usr/local/tomcat/webapps/ROOT/

 ---> Running in 358270130a99

index.html

Removing intermediate container 358270130a99

 ---> fa8a57190c35

Step 7/8 : RUN rm -rf in.tar.gz

 ---> Running in 427a4f99337b

Removing intermediate container 427a4f99337b

 ---> e1f986cea499

Step 8/8 : WORKDIR /usr/local/tomcat

 ---> Running in fac788f0e05c

Removing intermediate container fac788f0e05c

 ---> 9048b8a90988

Successfully built 9048b8a90988

Successfully tagged demo4:latest

3、创建容器

[root@localhost dockerdome3]# docker run -d --name=demo4 -p 8087:8080 demo4

7.4docker  build

Build an image from a Dockerfile

The docker build command builds Docker images from a Dockerfile and a “context”. A build’s context is the set of files located in the specified PATH or URL. The build process can refer to any of the files in the context. For example, your build can use a COPY instruction to reference a file in the context.

The URL parameter can refer to three kinds of resources: Git repositories, pre-packaged tarball contexts and plain text files.

7.5虚悬镜像

新的版本发布以后,镜像和标签转移到了新的镜像身上,旧的镜像标签变为<none>.

 

九、DOCKER图形化工具

9.1portainer

1、下载镜像

[root@localhost ~]# docker pull portainer/portainer

Using default tag: latest

latest: Pulling from portainer/portainer

94cfa856b2b1: Pull complete

49d59ee0881a: Pull complete

a2300fd28637: Pull complete

Digest: sha256:fb45b43738646048a0a0cc74fcee2865b69efde857e710126084ee5de9be0f3f

Status: Downloaded newer image for portainer/portainer:latest

docker.io/portainer/portainer:latest

2、启动容器

[root@localhost ~]# docker run -d --name=portainer -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock portainer/portainer

028d63f4f967e4a1242997afc7842c25d44822967f4cb5d1ee5f5f600dc004a2

3、访问并设置密码

http://192.168.1.8:9000   admin  1qaz2wsx

十、DOCKER COMPOSE

You can use compose subcommand, docker compose [-f <arg>...] [options] [COMMAND] [ARGS...], to build and manage multiple多重的 services in Docker containers.

负责快速的部署分布式应用。

10.1安装docker compose

Prerequisites

Docker Compose relies依赖 on Docker Engine for any meaningful work, so make sure you have Docker Engine installed either locally or remote, depending on your setup.

On desktop systems like Docker Desktop for Mac and Windows, Docker Compose is included as part of those desktop installs.

On Linux systems, first install the Docker Engine for your OS as described on the Get Docker page, then come back here for instructions on installing Compose on Linux systems.

To run Compose as a non-root user, see Manage Docker as a non-root user.

1、下载:https://github.com/docker/compose/releases

2、cp docker-compose-linux-x86_64 /usr/local

3、mv docker-compose-linux-x86_64 docker-compose

4、chmod 777 docker-compose

5、mv docker-compose bin

6、[root@localhost local]# docker-compose --version

Docker Compose version v2.3.3

10.2 术语

服务:一个应用容器,实际上可以运行多个相同的镜像的实例。

项目:由一组关联的应用容器组成一个完整的业务单元。

10.3 示例一

[root@localhost ~]# mkdir /opt/docker-cluster

[root@localhost ~]# cd /opt/docker-cluster/

vi docker-compose.yml

version: '3.0'

services:

   demo01:

    restart: always

    image: demo2

    container_name: demo1-8081

    ports:

      - 8081:8080

   demo02:

    restart: always

    image: demo2

    container_name: demo2-8082

    ports:

      - 8082:8080

   demo03:

    restart: always

    image: demo2

    container_name: demo2-8083

    ports:

      - 8083:8080

启动:

[root@localhost docker-cluster]# docker-compose up -d

[+] Running 4/4

关闭容器:

[root@localhost docker-cluster]# docker-compose stop

启动容器:

[root@localhost docker-cluster]# docker-compose start

posted @ 2022-03-20 21:54  中仕  阅读(43)  评论(0编辑  收藏  举报