[Docker]容器基礎(chǔ)實用教程

docker安裝基礎(chǔ)見前篇
基于Centos7安裝Docker

#查看docker版本
docker version

#-----------------------------------------控制臺輸出----------------------------------
Client:
 Cloud integration: 1.0.17
 Version:           20.10.8
 API version:       1.41
 Go version:        go1.16.6
 Git commit:        3967b7d
 Built:             Fri Jul 30 19:55:20 2021
 OS/Arch:           darwin/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.8
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.6
  Git commit:       75249d8
  Built:            Fri Jul 30 19:52:10 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.9
  GitCommit:        e25210fe30a0a703442421b0f60afac609f950a3
 runc:
  Version:          1.0.1
  GitCommit:        v1.0.1-0-g4144b63
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
#------------------------------------------------------------------------------------

鏡像基礎(chǔ)操作

#查找鏡像
docker search nginx
#----------------------------------------控制臺輸出-------------------------------------------------------------

NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                             Official build of Nginx.                        15480     [OK]       
jwilder/nginx-proxy               Automated Nginx reverse proxy for docker con…   2066                 [OK]
richarvey/nginx-php-fpm           Container running Nginx + PHP-FPM capable of…   818                  [OK]
jc21/nginx-proxy-manager          Docker container for managing Nginx proxy ho…   242                  
linuxserver/nginx                 An Nginx container, brought to you by LinuxS…   152                  
tiangolo/nginx-rtmp               Docker image with Nginx using the nginx-rtmp…   141                  [OK]
jlesage/nginx-proxy-manager       Docker container for Nginx Proxy Manager        135                  [OK]
alfg/nginx-rtmp                   NGINX, nginx-rtmp-module and FFmpeg from sou…   107                  [OK]
jasonrivers/nginx-rtmp            Docker images to host RTMP streams using NGI…   93                   [OK]
nginxdemos/hello                  NGINX webserver that serves a simple page co…   72                   [OK]
privatebin/nginx-fpm-alpine       PrivateBin running on an Nginx, php-fpm & Al…   57                   [OK]
nginx/nginx-ingress               NGINX and  NGINX Plus Ingress Controllers fo…   55                   
nginxinc/nginx-unprivileged       Unprivileged NGINX Dockerfiles                  51                   
staticfloat/nginx-certbot         Opinionated setup for automatic TLS certs lo…   24                   [OK]
nginxproxy/nginx-proxy            Automated Nginx reverse proxy for docker con…   20                   
nginx/nginx-prometheus-exporter   NGINX Prometheus Exporter for NGINX and NGIN…   19                   
schmunk42/nginx-redirect          A very simple container to redirect HTTP tra…   19                   [OK]
centos/nginx-112-centos7          Platform for running nginx 1.12 or building …   15                   
centos/nginx-18-centos7           Platform for running nginx 1.8 or building n…   13                   
raulr/nginx-wordpress             Nginx front-end for the official wordpress:f…   13                   [OK]
mailu/nginx                       Mailu nginx frontend                            9                    [OK]
sophos/nginx-vts-exporter         Simple server that scrapes Nginx vts stats a…   7                    [OK]
navidonskis/nginx-php5.6          Docker nginx + php5.6 on Ubuntu                 7                    [OK]
ansibleplaybookbundle/nginx-apb   An APB to deploy NGINX                          2                    [OK]
wodby/nginx                       Generic nginx                                   1                    [OK]
#-------------------------------------------------------------------------------------------------------------
#選擇一個nginx鏡像 使用命令下載鏡像
#拉取最新版本的鏡像
docker pull nginx

查看鏡像

docker images
#-----------------------------控制臺輸出-------------------------------------
REPOSITORY              TAG       IMAGE ID       CREATED      SIZE
phpdockerio/php73-fpm   latest    918fc516e945   2 days ago   162MB
nginx                   latest    ad4c705f24d3   7 days ago   133MB

通過鏡像啟動一個容器

docker run -i -t -d -p 80:80  nginx /bin/bash
#-----------------------------命令釋義-------------------------------------
run:運行
-i:交互式操作
-t:終端
-p:端口 [宿主機端口]:[docker內(nèi)部端口]
-d:后臺運行

查看已經(jīng)運行的容器

docker ps -a
#-----------------------------控制臺輸出---------------------------------------------------------------------------------
CONTAINER ID   IMAGE     COMMAND                  CREATED        STATUS        PORTS                               NAMES
78317fad8931   nginx     "/docker-entrypoint.…"   47 hours ago   Up 47 hours   0.0.0.0:80->80/tcp, :::80->80/tcp   nginx

進入已經(jīng)運行的容器

docker exec -i -t 78317fad8931 /bin/bash
#-----------------------------命令釋義-------------------------------------
方式一(推薦)-exec:退出容器終端芥备,不會導(dǎo)致容器的停止耍缴。
方式二(不推薦)-attach:退出容器終端滔以,會導(dǎo)致容器的停止瓜浸。

停止已啟動的容器

docker stop 78317fad8931

啟動已經(jīng)停止的容器

#重啟
docker restart 78317fad8931

#啟動
docker start 78317fad8931

刪除已經(jīng)停止的容器

# 注意刪除容器前需要先stop容器芍躏,否則會出現(xiàn)錯誤
docker rm 78317fad8931
#-----------------------------未停止容器錯誤提示-------------------------------------
Error response from daemon: You cannot remove a running container 78317fad893178246db3c52743c2770704319f6f991160bd3b4f0ddc97ec3949. 
Stop the container before attempting removal or force remove

刪除鏡像

# 注意刪除鏡像前需要先刪除容器皆怕,解除容器與鏡像關(guān)聯(lián)救欧,否則會出現(xiàn)錯誤
docker rmi nginx
#-----------------------------未刪除容器錯誤提示-------------------------------------
Error response from daemon: conflict: unable to remove repository reference "nginx" (must force) - container 78317fad8931 is using its referenced image ad4c705f24d3

搭建LNMP環(huán)境

安裝nginx

#查找鏡像
docker search nginx
#----------------------------------------控制臺輸出-------------------------------------------------------------

NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                             Official build of Nginx.                        15480     [OK]       
jwilder/nginx-proxy               Automated Nginx reverse proxy for docker con…   2066                 [OK]
richarvey/nginx-php-fpm           Container running Nginx + PHP-FPM capable of…   818                  [OK]
jc21/nginx-proxy-manager          Docker container for managing Nginx proxy ho…   242                  
linuxserver/nginx                 An Nginx container, brought to you by LinuxS…   152                  
tiangolo/nginx-rtmp               Docker image with Nginx using the nginx-rtmp…   141                  [OK]
jlesage/nginx-proxy-manager       Docker container for Nginx Proxy Manager        135                  [OK]
alfg/nginx-rtmp                   NGINX, nginx-rtmp-module and FFmpeg from sou…   107                  [OK]
jasonrivers/nginx-rtmp            Docker images to host RTMP streams using NGI…   93                   [OK]
nginxdemos/hello                  NGINX webserver that serves a simple page co…   72                   [OK]
privatebin/nginx-fpm-alpine       PrivateBin running on an Nginx, php-fpm & Al…   57                   [OK]
nginx/nginx-ingress               NGINX and  NGINX Plus Ingress Controllers fo…   55                   
nginxinc/nginx-unprivileged       Unprivileged NGINX Dockerfiles                  51                   
staticfloat/nginx-certbot         Opinionated setup for automatic TLS certs lo…   24                   [OK]
nginxproxy/nginx-proxy            Automated Nginx reverse proxy for docker con…   20                   
nginx/nginx-prometheus-exporter   NGINX Prometheus Exporter for NGINX and NGIN…   19                   
schmunk42/nginx-redirect          A very simple container to redirect HTTP tra…   19                   [OK]
centos/nginx-112-centos7          Platform for running nginx 1.12 or building …   15                   
centos/nginx-18-centos7           Platform for running nginx 1.8 or building n…   13                   
raulr/nginx-wordpress             Nginx front-end for the official wordpress:f…   13                   [OK]
mailu/nginx                       Mailu nginx frontend                            9                    [OK]
sophos/nginx-vts-exporter         Simple server that scrapes Nginx vts stats a…   7                    [OK]
navidonskis/nginx-php5.6          Docker nginx + php5.6 on Ubuntu                 7                    [OK]
ansibleplaybookbundle/nginx-apb   An APB to deploy NGINX                          2                    [OK]
wodby/nginx                       Generic nginx                                   1                    [OK]
#-------------------------------------------------------------------------------------------------------------

#選擇一個nginx鏡像 使用命令下載鏡像
#拉取最新版本的鏡像
docker pull nginx
#------------------------------------控制臺輸出----------------------------------
Using default tag: latest
latest: Pulling from library/nginx
Digest: sha256:853b221d3341add7aaadf5f81dd088ea943ab9c918766e295321294b035f3f3e
Status: Image is up to date for nginx:latest
docker.io/library/nginx:latest

運行容器

docker run --name nginx -p 80:80 -d nginx
#------------------------------------釋義----------------------------------
  --name 這里是別名定庵,使用docker ps 會最后顯示names
  -p  80:80    第一個80是服務(wù)器的端口吏饿,第二個80是docker容器端口,
  -d 要運行的容器名稱 這里是nginx

查看運行結(jié)果

CONTAINER ID   IMAGE     COMMAND                  CREATED      STATUS          PORTS                               NAMES
78317fad8931   nginx     "/docker-entrypoint.…"   2 days ago   Up 17 minutes   0.0.0.0:80->80/tcp, :::80->80/tcp   nginx

訪問nginx服務(wù)


image.png

安裝PHP

docker search php
#--------------------------------------------------控制臺輸出---------------------------------------
NAME                           DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
php                            While designed for web development, the PHP …   6158      [OK]       
phpmyadmin/phpmyadmin          A web interface for MySQL and MariaDB.          1137                 [OK]
phpmyadmin                     phpMyAdmin - A web interface for MySQL and M…   323       [OK]       
webdevops/php-nginx            Nginx with PHP-FPM                              209                  [OK]
php-zendserver                 Zend Server - the integrated PHP application…   199       [OK]       
webdevops/php-apache-dev       PHP with Apache for Development (eg. with xd…   145                  [OK]
webdevops/php-apache           Apache with PHP-FPM (based on webdevops/php)    119                  [OK]
osixia/phpldapadmin            phpLDAPadmin with easy configuration via env…   116                  
phpunit/phpunit                PHPUnit is a programmer-oriented testing fra…   82                   [OK]
nazarpc/phpmyadmin             phpMyAdmin as Docker container, based on off…   61                   [OK]
phpipam/phpipam-www            phpIPAM is an open-source web IP address man…   53                   
thecodingmachine/php           General-purpose ultra-configurable PHP images   38                   [OK]
jakzal/phpqa                   Docker image with quality analysis tools for…   37                   [OK]
pierrecdn/phpipam              phpIPAM web IP address management applicatio…   36                   [OK]
erikdubbelboer/phpredisadmin   Simple web interface to manage Redis databas…   32                   [OK]
chialab/php                    Adding common PHP extensions to some of the …   28                   [OK]
devilbox/php-fpm               PHP-FPM Docker images based on original PHP …   26                   
phpdockerio/php7-fpm           PHP 7 FPM base container for PHPDocker.io.      19                   [OK]
phpstan/phpstan                Docker container to check your application w…   19                   [OK]
phpdockerio/php73-fpm          PHP 7.3 FPM base container for PHPDocker.io.    18                   
appsvc/php                     Azure App Service php dockerfiles               16                   [OK]
arm32v7/php                    While designed for web development, the PHP …   14                   
phpipam/phpipam-cron           phpIPAM is an open-source web IP address man…   14                   
graze/php-alpine               Smallish php7 alpine image with some common …   12                   [OK]
phpdockerio/php7-cli           PHP 7 CLI base container image for PHPDocker…   2                    [OK]

選擇一個版本進行安裝

docker pull phpdockerio/php73-fpm

查看nginx 默認運行的路徑蔬浙,因為要通過-v命令將容器內(nèi)部的文件目錄掛載到宿主機的對應(yīng)目錄猪落,便于后期項目的管理
先進入已經(jīng)啟動的nginx容器

docker exec -it nginx /bin/bash
#查看nginx服務(wù)配置文件
vi /etc/nginx/conf.d/default.conf
#其中 root /usr/share/nginx/html 為容器的網(wǎng)絡(luò)應(yīng)用的根地址

創(chuàng)建并運行php容器

docker run -p 9000:9000 --name phpfpm -v /var/www/html:/usr/share/nginx/html -d phpdockerio/php73-fpm
#-p 將容器的9000端口與宿主機的9000端口進行映射

進入php 容器,找到路徑/usr/share/nginx/html
創(chuàng)建一個文件 index_test.php 文件

docker exec -it phpfpm bash
#進入容器
cd /usr/share/nginx/html/ 
vi test.php
#根據(jù)自己的喜好echo一句話進行測試
echo '測試PHP文件訪問';
  • 回到宿主機進入到 /var/www/html 已經(jīng)生成了test.php文件
  • 進入nginx容器配置訪問php 文件
  • 通過命令獲取到phpfpm容器的內(nèi)網(wǎng)ip地址
#方式一:通過命令行解析的方式進行ip的解析并獲取
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' phpfpm 
#方式二:通過檢查配置的方式返回所有配置信息
docker inspect  phpfpm 

方式二

方式一和方式二都可以獲取到IP地址畴博,只不過方式一的命令不太方便記憶笨忌,我一般常用方式二進行查詢配置
如上:我們獲取到172.17.0.3,這個ip 需要配置到nginx容器的/etc/nginx/conf.d/default.conf文件的配置中(熟悉nginx配置的同學(xué)也可以自己在/etc/nginx/conf.d/目錄下新建屬于自己的.conf文件進行配置)

配置nginx 支持php 文件訪問
docker exec -it nginx bash
#進入容器配置目錄
cd /etc/nginx/conf.d/
vi default.conf
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        root           /usr/share/nginx/html;
        #根據(jù)實際情況,配置成我們通過inspect命令獲取的ip
        fastcgi_pass   172.17.0.3:9000;
        fastcgi_index  index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

重啟nginx容器,即可通過IP訪問test.php

docker restart nginx
# http://ip/test.php

安裝mysql

docker search mysql
docker pull mysql
docker run -p 3306:3306 --name mymysql -v $PWD/conf:/etc/mysql/conf.d -v $PWD/logs:/logs -v $PWD/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql
-p 3306:3306:將容器的 3306 端口映射到宿主機的 3306 端口俱病。
-v -v $PWD/conf:/etc/mysql/conf.d:將主機當(dāng)前目錄下的 conf/my.cnf 掛載到容器的 /etc/mysql/my.cnf官疲。
-v $PWD/logs:/logs:將主機當(dāng)前目錄下的 logs 目錄掛載到容器的 /logs。
-v $PWD/data:/var/lib/mysql :將主機當(dāng)前目錄下的data目錄掛載到容器的 /var/lib/mysql 亮隙。
-e MYSQL_ROOT_PASSWORD=123456:初始化 root 用戶的密碼途凫。

常見問題

MYSQL錯誤

用navicat for mysql連接mysql發(fā)現(xiàn)報錯:Client does not support authentication protocol requested by server
解決方案:

#進入容器
docker exec -it [容器id] /bin/bash
#登陸mysql
mysql -uroot -p
#授權(quán)mysql的root用戶
GRANT ALL ON *.* TO 'root'@'%';
#
flush privileges;
#更新加密規(guī)則:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
#更新root用戶密碼
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '換成你的密碼';
#刷新權(quán)限
flush privileges;

保存后重新連接mysql,連接成功
造成這個問題的原因是因為:

  • 我們通過docker pull mysql安裝的mysql版本默認是最新的8.x
  • 在MySQL 8.0.11中溢吻,caching_sha2_password是默認的身份驗證插件颖榜,而不是以往的mysql_native_password
  • 所以我們需要手動調(diào)整一下加密規(guī)則即可
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子掩完,更是在濱河造成了極大的恐慌噪漾,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件且蓬,死亡現(xiàn)場離奇詭異欣硼,居然都是意外死亡,警方通過查閱死者的電腦和手機恶阴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門诈胜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人冯事,你說我怎么就攤上這事焦匈。” “怎么了昵仅?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵缓熟,是天一觀的道長。 經(jīng)常有香客問我摔笤,道長够滑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任吕世,我火速辦了婚禮彰触,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘命辖。我一直安慰自己况毅,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布尔艇。 她就那樣靜靜地躺著俭茧,像睡著了一般。 火紅的嫁衣襯著肌膚如雪漓帚。 梳的紋絲不亂的頭發(fā)上母债,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天,我揣著相機與錄音尝抖,去河邊找鬼毡们。 笑死,一個胖子當(dāng)著我的面吹牛昧辽,可吹牛的內(nèi)容都是我干的衙熔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼搅荞,長吁一口氣:“原來是場噩夢啊……” “哼红氯!你這毒婦竟也來了框咙?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤痢甘,失蹤者是張志新(化名)和其女友劉穎喇嘱,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體塞栅,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡者铜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了放椰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片作烟。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖砾医,靈堂內(nèi)的尸體忽然破棺而出拿撩,到底是詐尸還是另有隱情,我是刑警寧澤如蚜,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布压恒,位于F島的核電站,受9級特大地震影響怖亭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜坤检,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一兴猩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧早歇,春花似錦倾芝、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谱姓,卻和暖如春借尿,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背屉来。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工路翻, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人茄靠。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓茂契,卻偏偏與公主長得像,于是被迫代替她去往敵國和親慨绳。 傳聞我的和親對象是個殘疾皇子掉冶,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容