Docker Compose 容器編排 NET Core 6+MySQL 8+Nginx + Redis

語言: CN / TW / HK

環境:

CentOS 8.5.2111

Docker 20.10.10

Docker-Compose 2.1.0

服務:

db  redis  web nginx

NET Core 6+MySQL 8+Nginx + Redis

Kubernetes 又稱 K8s ,是叢集的 ,單機用 Docker Compose 編排容器 比較方便

cat /etc/system-release     #檢視版本

sudo yum update 

dnf -y update     #更新系統環境

先安裝 Docker Engine 和 Docker Compose

1. Docker  安裝

Docker三大核心概念:

映象(Image)

容器(Container)

倉庫(Repository)

https://docs.docker.com/compose/install/

https://cloud.tencent.com/document/product/213/46000

DockerHub映象加速器

使用加速器可以提升獲取Docker官方映象的速度

Docker Version不低於1.10時,建議直接通過daemon config進行配置

配置檔案/etc/docker/daemon.json(沒有時新建該檔案)

1. 建立一個Docker的配置檔案

sudo vim /etc/docker/daemon.json

2. 編寫配置檔案

{
"registry-mirrors": [
"https://個人申請的.mirror.aliyuncs.com",
"https://mirror.ccs.tencentyun.com",
"https://hub-mirror.c.163.com",
"https://mirror.baidubce.com"
]
}

阿里雲的個人加速器地址:https://cr.console.aliyun.com/cn-shenzhen/instances/mirrors

安裝 Docker

1.新增 Docker 軟體源 (docker-ce 社群版)

dnf config-manager --add-repo=https://mirrors.cloud.tencent.com/docker-ce/linux/centos/docker-ce.repo

2.檢視已新增的 Docker 軟體源

dnf list docker-ce

3.安裝 Docker

dnf install -y docker-ce

4.重新載入並重啟

sudo systemctl daemon-reload
sudo systemctl restart docker

5.設定Docker開機自啟

sudo systemctl enable docker

啟動docker

sudo systemctl start docker

關閉docker

sudo systemctl stop docker

更新docker-ce

yum update docker-ce

Docker 常用命令

docker info   #檢視資訊
docker version  #檢視版本
docker images #檢視已有映象
docker ps #檢視當前執行中的容器
docker ps -a #檢視所有容器,包括未執行中的
docker inspect netcoreip #檢視容器詳細資訊
docker exec -it nginx ls #進入容器檢視目錄結構與檔案

docker rm -f $(docker ps -aq) #刪除全部容器
docker rmi -f $(docker images -aq) #刪除全部映象


docker run -it ImageId /bin/bash #ImageId docker images 命令獲取, 退出容器:執行 exit 命令
docker exec -it 容器ID /bin/bash #進入後臺執行的容器
docker logs 容器ID/名稱 #如未檢視到剛才執行的容器,檢視啟動日誌排錯

強制刪除映象 例子

docker rmi -f 60c033c82171
docker rmi -f netcorezeng
docker rmi -f microsoft/dotnet

強制刪除容器 例子

docker rm -f mysql8

解除安裝Docker

sudo yum remove docker-ce docker-ce-cli containerd.io
sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd

2.Docker-Compose 容器編排

https://cloud.tencent.com/developer/article/1438222

V1 版本安裝(不用這個)

https://docs.docker.com/compose/install/

sudo curl -L "https://get.daocloud.io/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose #設定許可權

docker compose version #檢視版本

sudo rm /usr/local/bin/docker-compose #刪除

V2 版本安裝 (當前用這個)

https://docs.docker.com/compose/cli-command/#install-on-linux

https://github.com/docker/compose

1.建立目錄

mkdir -p /usr/local/lib/docker/cli-plugins

2.下載

curl -SL https://github.com/docker/compose/releases/download/v2.1.0/docker-compose-linux-x86_64 -o /usr/local/lib/docker/cli-plugins

上面方法 一般都會因為網路原因下載失敗 使用下面方法

下載 docker-compose-linux-x86_64 重新命名為 docker-compose 放到 /usr/local/lib/docker/cli-plugins

3.新增可執行許可權

chmod +x /usr/local/lib/docker/cli-plugins/docker-compose

3.Docker-Compose 配置

目錄結構:

工程目錄下 /home/docker_compose/docker-compose.yml

docker-compose.yml 配置

version: "3.9"
services:
   db:
        image: mysql
        container_name: mysql8
        restart: always
        volumes:
            - ./my.cnf:/etc/mysql/my.cnf
            - /home/data/mysql:/var/lib/mysql
        environment:
            MYSQL_ROOT_PASSWORD: "root密碼"
            MYSQL_DATABASE: "資料庫名稱"
            MYSQL_USER: "使用者名稱"
            MYSQL_PASSWORD: "使用者密碼"
        ports:
            - 3306:3306
        command:
            - --default-authentication-plugin=mysql_native_password
            - --character-set-server=utf8mb4
            - --collation-server=utf8mb4_bin

   redis:
        image: redis
        container_name: redis
        volumes:
            - /home/data/redis:/var/lib/redis
            - ./redis.conf:/usr/local/etc/redis/redis.conf
        ports:
            - 6379:6379
        command:
            redis-server /usr/local/etc/redis/redis.conf

   web:
        image: ${DOCKER_REGISTRY-}netcorezeng
        container_name: netcoreapp
        build:
          context: /home/app
          dockerfile: Dockerfile
        restart: always
        ports:
            - 5000:80
        depends_on:
            - db
            - redis
        environment:
           TZ: Asia/Shanghai

   nginx:
        image: nginx
        container_name: nginx
        restart: always
        ports:
            - 80:80
            - 443:443
        volumes:
            - ./nginx.conf:/etc/nginx/nginx.conf       
            - /home/sslcrt:/etc/nginx/cert
            - /home/log/nginx:/var/log/nginx
            - /home/app:/usr/share/nginx/html

my.cnf 配置

[client]

#socket = /usr/mysql/mysqld.sock

default-character-set = utf8mb4

[mysqld]

#pid-file = /var/run/mysqld/mysqld.pid
#socket = /var/run/mysqld/mysqld.sock
#datadir = /var/lib/mysql
#socket = /usr/mysql/mysqld.sock
#pid-file = /usr/mysql/mysqld.pid

datadir = /home/data/mysql
character_set_server = utf8mb4
collation_server = utf8mb4_bin
default-time_zone = '+8:00'
secure-file-priv= NULL

# Disabling symbolic-links is recommended to prevent assorted security risks

symbolic-links=0

# Custom config should go here

!includedir /etc/mysql/conf.d/

nginx.conf 配置

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}
http {
    log_format  main  '$remote_addr $http_x_forwarded_for - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen 80;
        server_name xx.com www.xx.com;      
       location / {
        root /usr/share/nginx/html;
        index index.html;
        proxy_pass http://web;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache_bypass $http_upgrade;
        add_header Access-Control-Allow-Methods *;
        add_header Access-Control-Allow-Origin $http_origin;
        } 
        }


    server {
        listen 443 ssl;
        server_name  xx.com www.xx.com;
        ssl_certificate "cert/1_bundle.crt";
        ssl_certificate_key "cert/2_.key";
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

       # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        root /usr/share/nginx/html;
        index index.html;
        proxy_pass http://web;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache_bypass $http_upgrade;
        add_header Access-Control-Allow-Methods *;
        add_header Access-Control-Allow-Origin $http_origin;
        }
    }
}

Dockerfile 配置

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM base AS final
WORKDIR /app
# 將本地應用拷貝到 容器/app 目錄下
COPY ./ ./
ENTRYPOINT ["dotnet", "NETCoreZeng.dll"]

1.建立工程目錄

mkdir /home/docker_compose

cd /home/docker_compose

2.建立 Dockerfile 模板檔案

注意:一定要是UNIX格式,不能是windows格式

/home/app/Dockerfile

3.配置服務檔案 docker-compose.yml

注意:不可以有製表符

語法錯誤: found character that cannot start any token (不可以有製表符)

did not find expected key

使用 YAML 時需要注意下面事項:

●不支援製表符 tab 鍵縮排,需要使用空格縮排

●通常開頭縮排2個空格

●字元後縮排1個空格,如冒號 : 、逗號 , 、橫槓 -

●用 # 號註釋

●如果包含特殊字元用單引號 ‘’ 引起來

●布林值必須用引號 “” 括起來

4.執行 Compose

錯誤提示:can't find a suitable configuration file in this directory or any parent: not found

切換到工程目錄下

cd /home/docker_compose

再執行

docker compose up -d

錯誤提示:yaml: line 33: did not find expected key(格式要規範 不能多空格 如 web db redis 前面的空格)

錯誤提示:cannot load certificate No such file or directory(證書預設目錄 /etc/nginx )

docker compose version #檢視版本
docker compose info
docker compose up #建立並啟動所有服務
docker compose up -d #在後臺所有啟動服務
docker compose images #所有映象
docker compose ps #檢視當前正在執行的容器
docker compose ps -a #檢視所有容器,包括未執行中的
docker compose stop #停止所有容器
docker compose stop web #停止某個服務
docker compose rm -f web #移除已經停止的服務容器
docker compose restart #重啟

docker compose logs -t --tail="10" #檢視nginx最新10條日誌

sudo rm /usr/local/lib/docker/cli-plugins/docker-compose #解除安裝 Docker Compose

容器時間與宿主機不一致

docker-compose.yml 裡面新增

environment:

TZ: Asia/Shanghai

容器之間連線

SERVICE 服務分別是 :db redis  web nginx

nginx.conf

proxy_pass http://web;

appsettings.json

 "ConnectionStrings": {
    "MySqlConnection": "server=db;xxxxxxxx;"
  },

最後

看起來 很多東西配置  其實 配置好 docker_compose 裡面幾個服務的配置   靈魂的東西都在裡面了

切換到工程目錄下

cd /home/docker_compose

再執行

docker compose up -d

就可以了