洛谷P1119 災後重建
-
Docker概述
Docker為什麼會出現?
考慮一種情況,有一種產品,有開發和上線兩種環境!應用環境,應用配置!
開發-----運維。問題:我在我的電腦上可以執行!版本更新,導致服務不可用!對於運維來說,考驗就十分大?
環境配置是十分麻煩的,每一臺機器都需要部署環境(叢集Redis,ES,Hadoop....)費時費力。
釋出一個專案 (jar+(Redis MySQL jdk ES)),專案能不能帶上環境安裝打包!
例如:
之前在一個伺服器配置一個應用的環境 Redis MySQL jdk Hadoop.配置起來超麻煩,不能夠跨平臺。
Windows開發,最後釋出在Linux!
傳統:開發jar,環境由運維來做!
現在:開發打包部署上線,一套流程做完!
Docker給以上問題提供瞭解決方案
舉個例子:
手機軟體開發流程:
java ---> apk --->釋出(應用商店) ---> 第三方使用apk --->安裝即可用
相對應的,Docker優化jar包開發部署流程:
java ---> jar(環境) ---> 打包帶上環境(映象)--->(Docker倉庫:對應應用商店)---> 下載我們釋出的映象 ---> 直接執行即可!
Docker的思想來自於集裝箱!
原本 JRE---多個應用(埠衝突)----原來都是交叉的!
隔離:Docker核心思想!打包裝箱!每個箱子都是互相隔離的。
Docker 通過隔離機制,可以將伺服器壓榨到機制
Docker歷史
2010年,幾個搞IT的年輕人,就在美國成立了一家公司dotCloud
做一些pass的雲端計算服務!LXC有關的容器技術!
他們將自己的技術(容器化技術)命名為Docker!
Docker剛剛誕生的時候,沒有引起行業的注意!dotCloud,就活不下去了!
開源
開放原始碼!
2013年,Docker開源!
Docker越來越多的人發現了docker的優點!火了,Docker每個月都會更新一個版本!
2014年4月9日,Docker1.0釋出!
Dcoker為什麼這麼火?十分的輕巧!
在容器技術出現之前我們使用的都是虛擬機器技術!
虛擬機器:在window中安裝一個Vmware,通過這個軟體我們可以虛擬出來一臺或者多臺電腦!缺點:笨重!
虛擬機器也是虛擬化技術,Docker容器技術,也是一種虛擬化技術!
vm:linux centos原生映象(一個電腦!) 隔離:需要開啟多臺虛擬機器! 幾個G
docker:隔離,映象(最核心的環境:4m+jdk+mysql) 十分的小巧,執行映象就可以了!小巧!幾個M
到現在,所有的開發/運維人員都必須掌握Docker!
聊聊Docker
Docker是基於Go語言開發的!開源專案!
Docker可以幹什麼?
之前的虛擬機器技術
- 資源佔用十分多
- 冗餘步驟多
- 啟動十分滿
容器技術不是模擬一個完整的作業系統
比較Docker和虛擬機器技術的不同:
傳統虛擬機器,虛擬出一個硬體,執行一個完整的作業系統,然後再這個系統上安裝和執行軟體
容器內的應用直接執行在宿主機的內容,容器是沒有核心的,也沒有虛擬我們的硬體,也沒有虛擬我們的硬體,所以就輕便了
每個容器之間是互相隔離,每個容器都有一個屬於自己的檔案系統,互不影響。
DevOps(開發,運維)
更快速的交付和部署
傳統:一堆幫助文件,安裝成簇
Docker:一鍵執行打包釋出測試,一鍵執行
更便捷的升級和擴縮容
使用了Docker之後,我們部署應用就和搭積木一樣!
專案打包成一個映象,擴充套件 伺服器B,伺服器B一鍵執行
更簡單的系統運維
在容器化之後,我們的開發,測試環境都是高度的一致。
更高效的計算資源利用
Docker是核心級別的虛擬化,可以在一個物理機上執行很多的容器例項!
-
Docker安裝
Docker架構圖
映象(iamge):
docker映象就好比一個模板,可以通過這個模板來建立容器服務,tomcat映象===》run===>tomcat01容器(提供伺服器)
通過這個容器可以建立多個容器(最終服務執行或者專案執行就是在容器中的)。
容器(container):
Docker利用容器技術,獨立執行一個或者一組應用,通過映象來建立的。
啟動,停止,刪除,基本命令!
目前就可以把這個容器理解為一個簡單的linux系統
倉庫(repository):
倉庫就是存放映象的地方!
倉庫可以分為共有倉庫和私有倉庫!
Docker Hub
阿里雲...都有容器伺服器(配置映象加速!)
Docker安裝步驟
環境準備
#系統核心是3.10以上的
[root@iZ2zec2gz7h1jgw8klihsnZ /]# uname -r 3.10.0-1062.18.1.el7.x86_64
#系統版本 [root@iZ2zec2gz7h1jgw8klihsnZ /]# cat /etc/os-release NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (Core)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:centos:centos:7" HOME_URL="https://www.centos.org/" BUG_REPORT_URL="https://bugs.centos.org/" CENTOS_MANTISBT_PROJECT="CentOS-7" CENTOS_MANTISBT_PROJECT_VERSION="7" REDHAT_SUPPORT_PRODUCT="centos" REDHAT_SUPPORT_PRODUCT_VERSION="7"
Centos7安裝
#1.解除安裝舊的版本 [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum remove docker \ > docker-client \ > docker-client-latest \ > docker-common \ > docker-latest \ > docker-latest-logrotate \ > docker-logrotate \ > docker-engine Loaded plugins: fastestmirror No Match for argument: docker No Match for argument: docker-client No Match for argument: docker-client-latest No Match for argument: docker-common No Match for argument: docker-latest No Match for argument: docker-latest-logrotate No Match for argument: docker-logrotate No Match for argument: docker-engine No Packages marked for removal
#2。安裝安裝包 [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum install -y yum-utils Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile base | 3.6 kB 00:00:00 epel | 4.7 kB 00:00:00 extras | 2.9 kB 00:00:00 updates | 2.9 kB 00:00:00 Resolving Dependencies --> Running transaction check ---> Package yum-utils.noarch 0:1.1.31-54.el7_8 will be installed --> Processing Dependency: python-kitchen for package: yum-utils-1.1.31-54.el7_8.noarch --> Processing Dependency: libxml2-python for package: yum-utils-1.1.31-54.el7_8.noarch --> Running transaction check ---> Package libxml2-python.x86_64 0:2.9.1-6.el7_9.6 will be installed --> Processing Dependency: libxml2 = 2.9.1-6.el7_9.6 for package: libxml2-python-2.9.1-6.el7_9.6.x86_64 ---> Package python-kitchen.noarch 0:1.1.1-5.el7 will be installed --> Processing Dependency: python-chardet for package: python-kitchen-1.1.1-5.el7.noarch --> Running transaction check ---> Package libxml2.x86_64 0:2.9.1-6.el7_2.3 will be updated ---> Package libxml2.x86_64 0:2.9.1-6.el7_9.6 will be an update ---> Package python-chardet.noarch 0:2.2.1-3.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ======================================================================================================================================= Package Arch Version Repository Size ======================================================================================================================================= Installing: yum-utils noarch 1.1.31-54.el7_8 base 122 k Installing for dependencies: libxml2-python x86_64 2.9.1-6.el7_9.6 updates 247 k python-chardet noarch 2.2.1-3.el7 base 227 k python-kitchen noarch 1.1.1-5.el7 base 267 k Updating for dependencies: libxml2 x86_64 2.9.1-6.el7_9.6 updates 668 k Transaction Summary ======================================================================================================================================= Install 1 Package (+3 Dependent packages) Upgrade ( 1 Dependent package) Total download size: 1.5 M Downloading packages: Delta RPMs disabled because /usr/bin/applydeltarpm not installed. (1/5): python-kitchen-1.1.1-5.el7.noarch.rpm | 267 kB 00:00:00 (2/5): libxml2-2.9.1-6.el7_9.6.x86_64.rpm | 668 kB 00:00:00 (3/5): yum-utils-1.1.31-54.el7_8.noarch.rpm | 122 kB 00:00:00 (4/5): python-chardet-2.2.1-3.el7.noarch.rpm | 227 kB 00:00:00 (5/5): libxml2-python-2.9.1-6.el7_9.6.x86_64.rpm | 247 kB 00:00:00 --------------------------------------------------------------------------------------------------------------------------------------- Total 4.9 MB/s | 1.5 MB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Updating : libxml2-2.9.1-6.el7_9.6.x86_64 1/6 Installing : libxml2-python-2.9.1-6.el7_9.6.x86_64 2/6 Installing : python-chardet-2.2.1-3.el7.noarch 3/6 Installing : python-kitchen-1.1.1-5.el7.noarch 4/6 Installing : yum-utils-1.1.31-54.el7_8.noarch 5/6 Cleanup : libxml2-2.9.1-6.el7_2.3.x86_64 6/6 Verifying : python-chardet-2.2.1-3.el7.noarch 1/6 Verifying : libxml2-2.9.1-6.el7_9.6.x86_64 2/6 Verifying : libxml2-python-2.9.1-6.el7_9.6.x86_64 3/6 Verifying : python-kitchen-1.1.1-5.el7.noarch 4/6 Verifying : yum-utils-1.1.31-54.el7_8.noarch 5/6 Verifying : libxml2-2.9.1-6.el7_2.3.x86_64 6/6 Installed: yum-utils.noarch 0:1.1.31-54.el7_8 Dependency Installed: libxml2-python.x86_64 0:2.9.1-6.el7_9.6 python-chardet.noarch 0:2.2.1-3.el7 python-kitchen.noarch 0:1.1.1-5.el7 Dependency Updated: libxml2.x86_64 0:2.9.1-6.el7_9.6 Complete!
#3.設定映象的倉庫 #這裡使用阿里雲的映象地址 http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum-config-manager \ > --add-repo \ > http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo Loaded plugins: fastestmirror adding repo from: http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo grabbing file http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo repo saved to /etc/yum.repos.d/docker-ce.repo
#清空yum索引 [root@iZ2zec2gz7h1jgw8klihsnZ /]# yum makecache fast Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile base | 3.6 kB 00:00:00 docker-ce-stable | 3.5 kB 00:00:00 epel | 4.7 kB 00:00:00 extras | 2.9 kB 00:00:00 updates | 2.9 kB 00:00:00 (1/2): docker-ce-stable/7/x86_64/updateinfo | 55 B 00:00:00 (2/2): docker-ce-stable/7/x86_64/primary_db | 76 kB 00:00:00 Metadata Cache Created [root@iZ2zec2gz7h1jgw8klihsnZ /]#
#4.安裝Docker引擎 #docker-ce 社群版 ee 企業版
[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin
#5.啟動Docker [root@iZ2zec2gz7h1jgw8klihsnZ /]# systemctl start docker
#使用docker version 測試是否安裝成功 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker version Client: Docker Engine - Community Version: 20.10.15 API version: 1.41 Go version: go1.17.9 Git commit: fd82621 Built: Thu May 5 13:16:58 2022 OS/Arch: linux/amd64 Context: default Experimental: true Server: Docker Engine - Community Engine: Version: 20.10.15 API version: 1.41 (minimum version 1.12) Go version: go1.17.9 Git commit: 4433bf6 Built: Thu May 5 13:15:18 2022 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.6.4 GitCommit: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16 runc: Version: 1.1.1 GitCommit: v1.1.1-0-g52de29d docker-init: Version: 0.19.0 GitCommit: de40ad0
#7.docker run hello-world [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 2db29710123e: Pull complete Digest: sha256:10d7d58d5ebd2a652f4d93fdd86da8f265f5318c6a73cc5b6a9798ff6d2b2e67 Status: Downloaded newer image for hello-world:latest Hello from Docker! This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://hub.docker.com/ For more examples and ideas, visit: https://docs.docker.com/get-started/
#8.檢視下載的這個 hello-world映象 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest feb5d9fea6a5 7 months ago 13.3kB
如何解除安裝Docker?
#1.Uninstall the Docker Engine, CLI, Containerd, and Docker Compose packages: yum remove docker-ce docker-ce-cli containerd.io
#2.Images, containers, volumes, or customized configuration files on your host are not automatically removed. To delete all images, containers, and volumes:
#刪除docker資源 /var/lib/ docker預設資源路徑 rm -rf /var/lib/docker rm -rf /var/lib/containerd
如何設定內部阿里雲映象加速?
1.找到阿里雲的映象加速器頁面
2.配置競相加速器
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ["https://ct2e6f86.mirror.aliyuncs.com"] } EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
Docker run的流程圖
底層原理:Docker是怎麼工作的?
Docker是一個Client-Server結構的系統,Docker的守護程序執行在主機,通過Socket從客戶端訪問!
DockerServer接收到Docker-Client的指令,就會執行這個命令!
Docker為什麼比虛擬機器快?
1.Docker有著比虛擬機器更少的抽象層。
2.Docker利用的是宿主機的核心,而VM需要的是Guest OS.
所以說,新建一個容器的時候,docker不需要虛擬機器一樣重新載入一個作業系統核心,避免引導。虛擬機器是載入Guest OS,分鐘級別;而docker是利用宿主機的作業系統,省略了複雜的過程,秒級!
Docker命令
幫助命令
#docker version 顯示docker版本資訊 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker version
Client: Docker Engine - Community
Version: 20.10.15
API version: 1.41
Go version: go1.17.9
Git commit: fd82621
Built: Thu May 5 13:16:58 2022
OS/Arch: linux/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.15
API version: 1.41 (minimum version 1.12)
Go version: go1.17.9
Git commit: 4433bf6
Built: Thu May 5 13:15:18 2022
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.6.4
GitCommit: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16
runc:
Version: 1.1.1
GitCommit: v1.1.1-0-g52de29d
docker-init:
Version: 0.19.0
GitCommit: de40ad0
#docker info 顯示Docker的系統資訊,包括映象和容器的數量
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker info
Client:
Context: default
Debug Mode: false
Plugins:
app: Docker App (Docker Inc., v0.9.1-beta3)
buildx: Docker Buildx (Docker Inc., v0.8.2-docker)
compose: Docker Compose (Docker Inc., v2.5.0)
scan: Docker Scan (Docker Inc., v0.17.0)
Server:
Containers: 1
Running: 0
Paused: 0
Stopped: 1
Images: 1
Server Version: 20.10.15
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
userxattr: false
Logging Driver: json-file
Cgroup Driver: cgroupfs
Cgroup Version: 1
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runtime.v1.linux runc io.containerd.runc.v2
Default Runtime: runc
Init Binary: docker-init
containerd version: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16
runc version: v1.1.1-0-g52de29d
init version: de40ad0
Security Options:
seccomp
Profile: default
Kernel Version: 3.10.0-1062.18.1.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 1.795GiB
Name: iZ2zec2gz7h1jgw8klihsnZ
ID: T2TL:C3VA:3VFE:KVI6:S4CL:X4HL:NNWR:GLBH:NDIC:Y35B:GGDE:TQVG
Docker Root Dir: /var/lib/docker
Debug Mode: false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://ct2e6f86.mirror.aliyuncs.com/
Live Restore Enabled: false
#docker --help 幫助命令 [root@iZ2zec2gz7h1jgw8klihsnZ /]# docker --help Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/root/.docker") -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") -D, --debug Enable debug mode -H, --host list Daemon socket(s) to connect to -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") --tls Use TLS; implied by --tlsverify --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") --tlskey string Path to TLS key file (default "/root/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: app* Docker App (Docker Inc., v0.9.1-beta3) builder Manage builds buildx* Docker Buildx (Docker Inc., v0.8.2-docker) compose* Docker Compose (Docker Inc., v2.5.0) config Manage Docker configs container Manage containers context Manage contexts image Manage images manifest Manage Docker image manifests and manifest lists network Manage networks node Manage Swarm nodes plugin Manage plugins scan* Docker Scan (Docker Inc., v0.17.0) secret Manage Docker secrets service Manage services stack Manage Docker stacks swarm Manage Swarm system Manage Docker trust Manage trust on Docker images volume Manage volumes Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders between a container and the local filesystem create Create a new container diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server exec Run a command in a running container export Export a container's filesystem as a tar archive history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on Docker objects kill Kill one or more running containers load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop one or more running containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers version Show the Docker version information wait Block until one or more containers stop, then print their exit codes Run 'docker COMMAND --help' for more information on a command. To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
映象命令
#docker images 檢視本地主機上的映象
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images --help
Usage: docker images [OPTIONS] [REPOSITORY[:TAG]]
List images
Options:
-a, --all Show all images (default hides intermediate images)
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
--no-trunc Don't truncate output
-q, --quiet Only show image IDs
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-world latest feb5d9fea6a5 7 months ago 13.3kB
#解釋
#REPOSITORY 映象的倉庫源
#TAG 映象的標籤
#IMAGE ID 映象的id
#CREATED 映象的建立時間
#SIZE 映象的大小
#docker search命令 搜尋映象
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search --help
Usage: docker search [OPTIONS] TERM
Search the Docker Hub for images
Options:
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print search using a Go template
--limit int Max number of search results (default 25)
--no-trunc Don't truncate output
#--filter=STARS=3000 這時候就會搜尋出STARS>3000的候選項
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12521 [OK]
mariadb MariaDB Server is a high performing open sou… 4816 [OK]
mysql/mysql-server Optimized MySQL Server Docker images. Create… 925 [OK]
#docker pull 下載映象 docker pull 映象名 [:tag]
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull --help
Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST]
Pull an image or a repository from a registry
Options:
-a, --all-tags Download all tagged images in the repository
--disable-content-trust Skip image verification (default true)
--platform string Set platform if server is multi-platform capable
-q, --quiet Suppress verbose output
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull mysql
Using default tag: latest#如果不寫tag,預設就是latest 最新版 docker pull mysql 等價於 docker pull mysql:latest
latest: Pulling from library/mysql
72a69066d2fe: Pull complete #分層下載,docker image的核心 聯合檔案系統
93619dbc5b36: Pull complete
99da31dd6142: Pull complete
626033c43d70: Pull complete
37d5d7efb64e: Pull complete
ac563158d721: Pull complete
d2ba16033dad: Pull complete
688ba7d5c01a: Pull complete
00e060b6d11d: Pull complete
1c04857f594f: Pull complete
4d7cfa90e6ea: Pull complete
e0431212d27d: Pull complete
Digest: sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709 #簽名
Status: Downloaded newer image for mysql:latest #
docker.io/library/mysql:latest #真實地址
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#############################################
#制定版本下載
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Already exists
93619dbc5b36: Already exists
99da31dd6142: Already exists
626033c43d70: Already exists
37d5d7efb64e: Already exists
ac563158d721: Already exists
d2ba16033dad: Already exists
0ceb82207cd7: Pull complete
37f2405cae96: Pull complete
e2482e017e53: Pull complete
70deed891d42: Pull complete
Digest: sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7
#docker rmi 刪除映象
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi --help
Usage: docker rmi [OPTIONS] IMAGE [IMAGE...]
Remove one or more images
Options:
-f, --force Force removal of the image
--no-prune Do not delete untagged parents
#指定ID刪除 docker rmi -f 容器id
#刪除多個容器 docker rmi -f 容器id1 容器id2 ...
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi -f 3218b38490ce
Untagged: mysql:latest
Untagged: mysql@sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709
Deleted: sha256:3218b38490cec8d31976a40b92e09d61377359eab878db49f025e5d464367f3b
Deleted: sha256:aa81ca46575069829fe1b3c654d9e8feb43b4373932159fe2cad1ac13524a2f5
Deleted: sha256:0558823b9fbe967ea6d7174999be3cc9250b3423036370dc1a6888168cbd224d
Deleted: sha256:a46013db1d31231a0e1bac7eeda5ad4786dea0b1773927b45f92ea352a6d7ff9
Deleted: sha256:af161a47bb22852e9e3caf39f1dcd590b64bb8fae54315f9c2e7dc35b025e4e3
Deleted: sha256:feff1495e6982a7e91edc59b96ea74fd80e03674d92c7ec8a502b417268822ff
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#回撥刪除
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi $(docker images -qa)
Untagged: mysql:5.7
Untagged: mysql@sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94
Deleted: sha256:c20987f18b130f9d144c9828df630417e2a9523148930dc3963e9d0dab302a76
Deleted: sha256:6567396b065ee734fb2dbb80c8923324a778426dfd01969f091f1ab2d52c7989
Deleted: sha256:0910f12649d514b471f1583a16f672ab67e3d29d9833a15dc2df50dd5536e40f
Deleted: sha256:6682af2fb40555c448b84711c7302d0f86fc716bbe9c7dc7dbd739ef9d757150
Deleted: sha256:5c062c3ac20f576d24454e74781511a5f96739f289edaadf2de934d06e910b92
Deleted: sha256:8805862fcb6ef9deb32d4218e9e6377f35fb351a8be7abafdf1da358b2b287ba
Deleted: sha256:872d2f24c4c64a6795e86958fde075a273c35c82815f0a5025cce41edfef50c7
Deleted: sha256:6fdb3143b79e1be7181d32748dd9d4a845056dfe16ee4c827410e0edef5ad3da
Deleted: sha256:b0527c827c82a8f8f37f706fcb86c420819bb7d707a8de7b664b9ca491c96838
Deleted: sha256:75147f61f29796d6528486d8b1f9fb5d122709ea35620f8ffcea0e0ad2ab0cd0
Deleted: sha256:2938c71ddf01643685879bf182b626f0a53b1356138ef73c40496182e84548aa
Deleted: sha256:ad6b69b549193f81b039a1d478bc896f6e460c77c1849a4374ab95f9a3d2cea2
Error response from daemon: conflict: unable to delete feb5d9fea6a5 (must be forced) - image is being used by stopped container 8b4dd872b6e7
容器命令
我們有了映象才可以常見容器,linux,下載一個linux映象來測試學習
#下載一個centos映象
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search centos
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
centos The official build of CentOS. 7133 [OK]
centos/systemd systemd enabled base container. 108 [OK]
centos/mysql-57-centos7 MySQL 5.7 SQL database server 94
centos/postgresql-96-centos7 PostgreSQL is an advanced Object-Relational … 45
centos/httpd-24-centos7 Platform for running Apache httpd 2.4 or bui… 44
centos/php-56-centos7 Platform for building and running PHP 5.6 ap… 34
centos/mysql-56-centos7 MySQL 5.6 SQL database server 22
kasmweb/centos-7-desktop CentOS 7 desktop for Kasm Workspaces 19
centos/postgresql-10-centos7 PostgreSQL is an advanced Object-Relational … 19
centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 16
centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 14
centos/mariadb-101-centos7 MariaDB 10.1 SQL database server 13
centos/mongodb-36-centos7 MongoDB NoSQL database server 8
centos/mariadb-102-centos7 MariaDB 10.2 SQL database server 6
centos/redis-32-centos7 Redis in-memory data structure store, used a… 6
kasmweb/core-centos-7 CentOS 7 base image for Kasm Workspaces 3
centos/ruby-25-centos7 Platform for building and running Ruby 2.5 a… 3
continuumio/centos5_gcc5_base 3
centos/mongodb-34-centos7 MongoDB NoSQL database server 3
ibmcom/fhe-toolkit-centos The IBM Fully Homomorphic Encryption (FHE) T… 0
ibmcom/fhe-toolkit-centos-amd64 The IBM Fully Homomorphic Encryption (FHE) T… 0
datadog/centos-i386 0
bitnami/centos-extras-base 0
bitnami/centos-base-buildpack Centos base compilation image 0 [OK]
centos/nginx-110-centos7 Platform for running nginx 1.10 or building … 0
[root@iZ2zec2gz7h1jgw8klihsnZ /]# doucker pull centos
-bash: doucker: command not found
[root@iZ2zec2gz7h1jgw8klihsnZ /]# douker pull centos
-bash: douker: command not found
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
a1d0c7532777: Pull complete
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest
#docker run 新建容器啟動
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
#常見引數說明
#--name="容器名" 容器名字 tomcat01 tomcat02,用來區分容器
#-d 後臺執行
#-it 使用互動方式執行,進入容器檢視內容
#-p 制定容器埠 -p 8080:8080
#-p使用方式
#-p ip:主機埠:容器埠
#-p 主機埠:容器埠(常用)
#-p 容器埠
#-P 隨機制定埠
Run a command in a new container
Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
-a, --attach list Attach to STDIN, STDOUT or STDERR
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device list Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--cgroup-parent string Optional parent cgroup for the container
--cgroupns string Cgroup namespace to use (host|private)
'host': Run the container in the Docker host's cgroup namespace
'private': Run the container in its own private cgroup namespace
'': Use the cgroup namespace as configured by the
default-cgroupns-mode option on the daemon (default)
--cidfile string Write the container ID to the file
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container
--device-cgroup-rule list Add a rule to the cgroup allowed devices list
--device-read-bps list Limit read rate (bytes per second) from a device (default [])
--device-read-iops list Limit read rate (IO per second) from a device (default [])
--device-write-bps list Limit write rate (bytes per second) to a device (default [])
--device-write-iops list Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers
--dns-option list Set DNS options
--dns-search list Set custom DNS search domains
--domainname string Container NIS domain name
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
--expose list Expose a port or a range of ports
--gpus gpu-request GPU devices to add to the container ('all' to pass all GPUs)
--group-add list Add additional groups to join
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-start-period duration Start period for the container to initialize before starting health-retries countdown
(ms|s|m|h) (default 0s)
--health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
-i, --interactive Keep STDIN open even if not attached
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
--kernel-memory bytes Kernel memory limit
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
--log-driver string Logging driver for the container
--log-opt list Log driver options
--mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--mount mount Attach a filesystem mount to the container
--name string Assign a name to the container
--network network Connect a container to a network
--network-alias list Add network-scoped alias for the container
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--platform string Set platform if server is multi-platform capable
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--pull string Pull image before running ("always"|"missing"|"never") (default "missing")
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options
--shm-size bytes Size of /dev/shm
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string Working directory inside the container
#################################################################################
#測試docker run 命令的使用
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run -it centos /bin/bash #啟動並進入容器
[root@4cc85a317196 /]# ls #檢視容器內的centos,基礎版本,很多命令都是不完善的
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@4cc85a317196 /]# exit #從容器中退回主機
exit
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#docker ps檢視執行中的容器
# 列出當前正在執行的容器
#-a 列出當前正在執行的容器,帶出歷史執行過的容器
#-n=? 顯示最近建立的容器
#-q 只顯示容器的ID
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps #列出當前正在執行中的容器
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -a #列出
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4cc85a317196 centos "/bin/bash" 3 minutes ago Exited (0) About a minute ago ecstatic_robinson
8b4dd872b6e7 hello-world "/hello" 2 hours ago Exited (0) 2 hours ago admiring_gould
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -aq
4cc85a317196
8b4dd872b6e7
#退出容器相關命令
exit #直接容器停止並退出
ctrl+p+q #容器不停止退出
#刪除容器
docker rm 容器id #刪除指定容器 不能刪除正在執行中的容器, docker rm -f 容器id強制刪除容器
docker rm -f $(docker ps -aq) #刪除所有容器
docker ps -a|xargs docker rm #通過管道符刪除所有容器
#啟動和停止容器的操作
docker start 容器id #啟動容器
docker restart 容器id #重啟容器
docker stop 容器id #停止當前執行容器
docker kill 容器id #強制停止當前容器
#後臺啟動容器
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run -d --name="centos02" centos
1a0f5a321118bd793f70fabdd868e2a543ba18ee83838fa766a525a7869d15a8
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1a0f5a321118 centos "/bin/bash" 6 seconds ago Exited (0) 5 seconds ago centos02
8be72caaa4a7 centos "/bin/bash" 8 minutes ago Up 8 minutes centos01
4cc85a317196 centos "/bin/bash" 20 minutes ago Up About a minute ecstatic_robinson
8b4dd872b6e7 hello-world "/hello" 2 hours ago Exited (0) 2 hours ago admiring_gould
#########問題:docker ps 發現啟動的命名為"centos02"的容器狀態停止了
#########常見的坑:容器使用後臺執行,就必須要有一個前臺程序,docker發現該容器沒有應用,就會自動停止
#########Nginx,容器啟動後,發現自己沒有提供服務,就會立刻停止(它自己就會認為沒有程式了)
#docker logs 檢視日誌命令
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker logs --help
Usage: docker logs [OPTIONS] CONTAINER
Fetch the logs of a container
Options:
--details Show extra details provided to logs
-f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
-n, --tail string Number of lines to show from the end of the logs (default "all")
-t, --timestamps Show timestamps
--until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
docker logs -f -t 容器id, 沒有日誌
#自己編寫一個shell指令碼
root@iZ2zec2gz7h1jgw8klihsnZ /]# docker logs -f -t --tail=10 87c4f1ebc327 #--tail=number 要顯示的日誌條數
2022-05-06T11:22:38.879103869Z kuangshen
2022-05-06T11:22:39.881477695Z kuangshen
2022-05-06T11:22:40.886896828Z kuangshen
2022-05-06T11:22:41.888957987Z kuangshen
2022-05-06T11:22:42.891040169Z kuangshen
2022-05-06T11:22:43.893141573Z kuangshen
2022-05-06T11:22:44.895206262Z kuangshen
2022-05-06T11:22:45.897327442Z kuangs
#docker top 容器id 檢視容器中的程序資訊
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
87c4f1ebc327 centos "/bin/sh -c 'while t…" 3 minutes ago Up 3 minutes sad_babbage
8be72caaa4a7 centos "/bin/bash" About an hour ago Up About an hour centos01
4cc85a317196 centos "/bin/bash" About an hour ago Up 57 minutes ecstatic_robinson
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker top 87c4f1ebc327
UID PID PPID C STIME TTY TIME CMD
root 18172 18153 0 19:21 ? 00:00:00 /bin/sh -c while true;do echo kuangshen;sleep 1;done
root 18533 18172 0 19:25 ? 00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
[root@iZ2zec2gz7h1jgw8klihsnZ /]#
#docker inspect 容器id #檢視映象容器的元資料
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker inspect 87c4f1ebc327 [ { "Id": "87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8", "Created": "2022-05-06T11:21:30.439030234Z", "Path": "/bin/sh", "Args": [ "-c", "while true;do echo kuangshen;sleep 1;done" ], "State": { "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 18172, "ExitCode": 0, "Error": "", "StartedAt": "2022-05-06T11:21:30.731601995Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6", "ResolvConfPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/resolv.conf", "HostnamePath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/hostname", "HostsPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/hosts", "LogPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8-json.log", "Name": "/sad_babbage", "RestartCount": 0, "Driver": "overlay2", "Platform": "linux", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "", "ExecIDs": null, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LogConfig": { "Type": "json-file", "Config": {} }, "NetworkMode": "default", "PortBindings": {}, "RestartPolicy": { "Name": "no", "MaximumRetryCount": 0 }, "AutoRemove": false, "VolumeDriver": "", "VolumesFrom": null, "CapAdd": null, "CapDrop": null, "CgroupnsMode": "host", "Dns": [], "DnsOptions": [], "DnsSearch": [], "ExtraHosts": null, "GroupAdd": null, "IpcMode": "private", "Cgroup": "", "Links": null, "OomScoreAdj": 0, "PidMode": "", "Privileged": false, "PublishAllPorts": false, "ReadonlyRootfs": false, "SecurityOpt": null, "UTSMode": "", "UsernsMode": "", "ShmSize": 67108864, "Runtime": "runc", "ConsoleSize": [ 0, 0 ], "Isolation": "", "CpuShares": 0, "Memory": 0, "NanoCpus": 0, "CgroupParent": "", "BlkioWeight": 0, "BlkioWeightDevice": [], "BlkioDeviceReadBps": null, "BlkioDeviceWriteBps": null, "BlkioDeviceReadIOps": null, "BlkioDeviceWriteIOps": null, "CpuPeriod": 0, "CpuQuota": 0, "CpuRealtimePeriod": 0, "CpuRealtimeRuntime": 0, "CpusetCpus": "", "CpusetMems": "", "Devices": [], "DeviceCgroupRules": null, "DeviceRequests": null, "KernelMemory": 0, "KernelMemoryTCP": 0, "MemoryReservation": 0, "MemorySwap": 0, "MemorySwappiness": null, "OomKillDisable": false, "PidsLimit": null, "Ulimits": null, "CpuCount": 0, "CpuPercent": 0, "IOMaximumIOps": 0, "IOMaximumBandwidth": 0, "MaskedPaths": [ "/proc/asound", "/proc/acpi", "/proc/kcore", "/proc/keys", "/proc/latency_stats", "/proc/timer_list", "/proc/timer_stats", "/proc/sched_debug", "/proc/scsi", "/sys/firmware" ], "ReadonlyPaths": [ "/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger" ] }, "GraphDriver": { "Data": { "LowerDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb-init/diff:/var/lib/docker/overlay2/f0b92d162490bac978b459ad6cc2a7e24cf8a2b60c0f10b0e9c66d0638936237/diff", "MergedDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/merged", "UpperDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/diff", "WorkDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/work" }, "Name": "overlay2" }, "Mounts": [], "Config": { "Hostname": "87c4f1ebc327", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/sh", "-c", "while true;do echo kuangshen;sleep 1;done" ], "Image": "centos", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": { "org.label-schema.build-date": "20210915", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS" } }, "NetworkSettings": { "Bridge": "", "SandboxID": "3f9ef183276fa2747b7fd8abd5b9eccfc62bd17e7e2ac2036f79625a395bee89", "HairpinMode": false, "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "Ports": {}, "SandboxKey": "/var/run/docker/netns/3f9ef183276f", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null, "EndpointID": "ed5f048fa928944e057d1c1b068f89253ace616e56b9dc4a9aada0916c8c959c", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAddress": "172.17.0.4", "IPPrefixLen": 16, "IPv6Gateway": "", "MacAddress": "02:42:ac:11:00:04", "Networks": { "bridge": { "IPAMConfig": null, "Links": null, "Aliases": null, "NetworkID": "feb3d1ca8d81153ef6a23103a75495fc92bc2776d479880673eafebf84c46e11", "EndpointID": "ed5f048fa928944e057d1c1b068f89253ace616e56b9dc4a9aada0916c8c959c", "Gateway": "172.17.0.1", "IPAddress": "172.17.0.4", "IPPrefixLen": 16, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:04", "DriverOpts": null } } } } ]
#進入當前正在執行的容器
#方式一
#docker exec -it 容器id bashshell #我們通常容器都是使用後臺方式進行的,需要進入容器,修改一些配置 #命令 root@iZ2zec2gz7h1jgw8klihsnZ /]# docker exec -it 8be72caaa4a7 /bin/bash [root@8be72caaa4a7 /]# ls bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var [root@8be72caaa4a7 /]#
#方式二
#docker attach 容器id
#正在執行當前的程式碼。。。
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker attach --help
Usage: docker attach [OPTIONS] CONTAINER
Attach local standard input, output, and error streams to a running container
Options:
--detach-keys string Override the key sequence for detaching a container
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)
#####################################
#docker exec 和 docker attach的區別
#docker exec #進入容器後開啟一個新的終端,可以在裡面操作(常用)
#docker attach #進入容器後正在執行的終端,不會啟動新的程序!
#docker cp 容器id:/目錄/檔案 主機目錄 容器內容從容器拷貝到主機上
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker cp 4cc85a317196:/home/tmp_cp.java /home
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# cd /home
[root@iZ2zec2gz7h1jgw8klihsnZ home]# ls
tmp_cp.java wgy
[root@iZ2zec2gz7h1jgw8klihsnZ home]#
###################################
#docker是一個手動過程,為了我們使用 -v 卷的技術,可以實現,自動同步 /home /home
操作命令總結
Docker安裝Nginx
#Docker安裝Nginx #步驟1 搜尋映象 docker search nginx #步驟2 下載映象 docker pull nginx #步驟3 檢視映象 docker images [root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d --name nginx01 -p:3344:80 nginx #後臺執行nginx容器 45114e9800fba66d6c9c5e05180014a3a901e9df19f3bb393406cd104038ef48 [root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 45114e9800fb nginx "/docker-entrypoint.…" 4 seconds ago Up 4 seconds 0.0.0.0:3344->80/tcp nginx01 87c4f1ebc327 centos "/bin/sh -c 'while t…" 20 hours ago Up 20 hours sad_babbage [root@iZ2zec2gz7h1jgw8klihsnZ ~]# curl localhost:3344 # curl 是一種命令列工具,作用是發出網路請求,然後獲取資料,顯示在"標準輸出"(stdout)上面。它支援多種協議,下面列舉其常用功能。 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> html { color-scheme: light dark; } body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html>
此處需要講解一下 -p 宿主機埠:容器埠 的作用
使用者無法直接訪問容器埠,我們使用-p,來將宿主機埠與容器埠進行繫結(打通埠),從而使用者可以通過宿主機埠訪問到容器埠,進而訪問容器埠相應的服務。
此時可以通過宿主機的埠:ip訪問nginx容器啟動的nginx服務的歡迎頁面
#進入到nginx容器內部
root@8597a6f04b0d:/usr/sbin# cd /etc/nginx
root@8597a6f04b0d:/etc/nginx# ls
conf.d fastcgi_params mime.types modules nginx.conf scgi_params uwsgi_params
root@8597a6f04b0d:/etc/nginx# cat nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
問題:每次改動nginx配置檔案,都需要進入容器內部?十分地麻煩,我要是可以在容器外部提供一個對映路徑,達到在容器外部修改檔案,容器內部就可以自動修改的目的。
Docker部署Tomcat
dockerHub官方提供的安裝命令
docker run -it --rm tomcat:9.0
#我們之前的啟動都是後臺,停止了容器之後,容器還是可以看到 docker run -it --rm 一般用來測試,執行完就刪除
學習過程中部署Docker的安裝命令
#下載tomcat映象 docker pull tomcat
#執行tomcat容器
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d -p 3345:8080 --name tomcat01 tomcat
405e34e4755157541f480adeb758c76504266c14cd63ccc2034e762ba5dc616c
#進入到tomcat容器中
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker exec -it 405e34e47551 /bin/bash
root@405e34e47551:/usr/local/tomcat# whereis tomcat
tomcat: /usr/local/tomcat
root@405e34e47551:/usr/local/tomcat# ls
BUILDING.txt LICENSE README.md RUNNING.txt conf logs temp webapps.dist
CONTRIBUTING.md NOTICE RELEASE-NOTES bin lib native-jni-lib webapps work
root@405e34e47551:/usr/local/tomcat# cd webapps #此時發現webapps目錄下為空
root@405e34e47551:/usr/local/tomcat/webapps#
####發現問題 webapps目錄下什麼都沒有,阿里雲映象預設是最小映象,所有不必要的映象都剔除掉
####保證最小可執行的環境
以後要部署專案,每次都要進入容器是不是十分麻煩?要是可以在容器外部提供一個對映路徑,webapps,在外部放置專案就自動同步到內部就好了!
部署es+kibana
#es 暴露的埠非常多
#es 十分的耗記憶體
#es 的資料一般都放置到安全目錄,
#--net somework 網路配置
#docker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:tag
#啟動docker容器服務
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
Unable to find image 'elasticsearch:7.6.2' locally
7.6.2: Pulling from library/elasticsearch
ab5ef0e58194: Pull complete
c4d1ca5c8a25: Pull complete
941a3cc8e7b8: Pull complete
43ec483d9618: Pull complete
c486fd200684: Pull complete
1b960df074b2: Pull complete
1719d48d6823: Pull complete
Digest: sha256:1b09dbd93085a1e7bca34830e77d2981521a7210e11f11eda997add1c12711fa
Status: Downloaded newer image for elasticsearch:7.6.2
5bed8e09f3e4644ac7f99027810c65d521325bd99a57dd8edb7836f6cbd3d6d1
#docker status 檢視cpu的狀態
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker ps -aq
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
ec208095a057 elasticsearch 98.01% 1.244GiB / 1.795GiB 69.34% 0B / 0B 207MB / 246kB 26
#關閉當前es容器,增加記憶體限制,修改配置檔案, -e 環境配置修改
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# curl localhost:9200
{
"name" : "71773db7f220",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "3CayxfTES_mRBzO-fDlurw",
"version" : {
"number" : "7.6.2",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
"build_date" : "2020-03-26T06:34:37.794943Z",
"build_snapshot" : false,
"lucene_version" : "8.4.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
es和kibana互動原理
視覺化
portainer
Docker圖形化管理工具,提供一個後臺面板供我們操作!
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d -p 3346:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer Unable to find image 'portainer/portainer:latest' locally 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 9f66596e5679ff98d0ce8ae51e36dc35d5dcbe489c6750e6f68471217cd55adb
Rancher(CI/CD再用)
Docker映象
映象是什麼?
映象是一個輕量級,可執行的獨立軟體包,用來打包軟體執行環境和基於執行環境開發的軟體,它包含某個軟體所需的所有內容,包含程式碼,執行時,庫,環境變數和配置檔案。
所有的應用,直接打包成為一個docker映象,就可以直接跑起來!
如何得到映象?
- 從遠端倉庫下載
- 朋友拷貝給你
- 自己製作一個映象DockerFile
映象載入原理
Docker是一個輕量級的、可執行的獨立軟體包,將一個應用程式和環境打包成為一個檔案包,這個打包好的檔案包就是Docker映象。只有通過映象檔案才能生成容器例項。。映象檔案是分層的,底層採用聯合檔案系統來實現。
聯合檔案系統(UnionFS)
聯合檔案系統是一個輕量級、高效能的檔案系統;他支援對檔案系統的修改作為一次提交來一層層疊加;同時可以將不同的目錄掛載到同一個檔案系統下.UnionFs是Docker映象的基礎。可以通過分層來繼承基礎映象,提高檔案的複用。
Docker映象載入原理
bootfs(boot file system) 主要包含bootloader和kernel, bpotloader 主要是引導載入kernel,當我們載入映象的時候,會通過bootloader載入kernal,Docker映象最底層是bootfs,當boot載入完成後整個kernal核心都在記憶體中了,bootfs也就可以解除安裝,值得注意的是,bootfs是被所有映象共用的,許多映象images都是在base image(rootfs)基礎上疊加的。
rootfs (root file system),在bootfs之 上.包含的就是典型Linux系統中的/dev, /proc, /bin, /etc等標準目錄和檔案。rootfs就是 各種不同的作業系統發行版,比如Ubuntu, Centos等等 。
分層原理介紹
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker pull redis Using default tag: latest latest: Pulling from library/redis a2abf6c4d29d: Already exists c7a4e4382001: Pull complete 4044b9ba67c9: Pull complete c8388a79482f: Pull complete 413c8bb60be2: Pull complete 1abfd3011519: Pull complete Digest: sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339 Status: Downloaded newer image for redis:latest docker.io/library/redis:latest [root@iZ2zec2gz7h1jgw8klihsnZ ~]#
#docker inspect redis 看到配置檔案中有一個Layers,裡面包含
"Layers": [ "sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f", "sha256:9b24afeb7c2f21e50a686ead025823cd2c6e9730c013ca77ad5f115c079b57cb", "sha256:4b8e2801e0f956a4220c32e2c8b0a590e6f9bd2420ec65453685246b82766ea1", "sha256:529cdb636f61e95ab91a62a51526a84fd7314d6aab0d414040796150b4522372", "sha256:9975392591f2777d6bf4d9919ad1b2c9afa12f9a9b4d260f45025ec3cc9b18ed", "sha256:8e5669d8329116b8444b9bbb1663dda568ede12d3dbcce950199b582f6e94952" ]
特點
Docker映象都是隻讀的,當容器啟動時,一個新的可寫層被載入到映象的頂部!
這一層是我們經常說的容器層,容器之下的都叫做映象層
如何提交(Commit)一個映象?
-
容器資料卷
-
DockerFile
-
Docker網路原理
-
IDEA整合Docker
-
Docker Compose
-
Docker Swarm
-
CI\CD Jenkins