# 九.Nginx

前言

配置 nginx docker,挂载目录放到docker外部,方便修改配置与存放资源以及查看日志

# 1.获取镜像

docker pull nginx
1

# 2.拷贝配置

  • 启动 nginx 容器
docker run --name nginx -p 90:80 -d nginx
1
  • 创建挂载目录xxx
mkdir -p /Users/zhoubichuan/nginx/nginx/conf
mkdir -p /Users/zhoubichuan/nginx/nginx/log
mkdir -p /Users/zhoubichuan/nginx/nginx/html
1
2
3
  • 修改配置文件为本地
docker cp nginx:/etc/nginx/nginx.conf /Users/zhoubichuan/nginx/conf/nginx.conf
docker cp nginx:/etc/nginx/conf.d /Users/zhoubichuan/nginx/conf/conf.d
docker cp nginx:/usr/share/nginx/html /Users/zhoubichuan/nginx/
1
2
3
  • 删除容器
# 找到nginx对应的容器id
docker ps -a
# 关闭该容器
docker stop nginx
# 删除该容器
docker rm nginx
1
2
3
4
5
6

# 3.配置 nginx

    server {
        listen       80;
        server_name  81.71.127.69;
        location ~*^.+$ {
            root   /usr/src/zhoubichuan/prod;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }
    }
1
2
3
4
5
6
7
8
9

# 4.启动镜像

docker run \
-p 80:80 \
--name nginx \
--network dockerbetweennetwork \
-v /Users/zhoubichuan/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /Users/zhoubichuan/nginx/conf/conf.d:/etc/nginx.conf.d \
-v /Users/zhoubichuan/nginx/log:/var/log/nginx \
-v /Users/zhoubichuan/nginx/html:/usr/share/nginx/html \
-d nginx:latest
1
2
3
4
5
6
7
8
9
命令 描述
–name nginx 启动容器的名字
-d 后台运行
--network dockerbetweennetwork 桥接网络
-p 80:80 将容器的 80(后面那个) 端口映射到主机的 80(前面那个) 端口
-v /Users/zhoubichuan/nginx/conf/nginx.conf:/etc/nginx/nginx.conf 挂载 nginx.conf 配置文件
-v /Users/zhoubichuan/nginx/conf/conf.d:/etc/nginx.conf.d 挂载 nginx 配置文件
-v /Users/zhoubichuan/nginx/log:/var/log/nginx 挂载 nginx 日志文件
-v /Users/zhoubichuan/nginx/html:/usr/share/nginx/html 挂载 nginx 内容
nginx:latest 本地运行的版本
\ shell 命令换行

# 5.Dockerfile

# 6.docker-compose

version: "3.8"

services:
  web:
    image: nginx:1.23-alpine
    ports:
      - "80:80"
    volumes:
      - ./html:/usr/share/nginx/html
    restart: unless-stopped
1
2
3
4
5
6
7
8
9
10
docker-compose up -d
1
  • 生产配置
version: "3.8"

services:
  nginx:
    image: nginx:1.23-alpine
    container_name: production_nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./config/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./config/conf.d:/etc/nginx/conf.d
      - ./html:/usr/share/nginx/html
      - ./logs:/var/log/nginx
      - ./certs:/etc/ssl/certs
    environment:
      - TZ=Asia/Shanghai
      - NGINX_ENVSUBST_OUTPUT_DIR=/etc/nginx/conf.d
    networks:
      - frontend
    deploy:
      resources:
        limits:
          cpus: "1.5"
          memory: 512M
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 30s
      timeout: 3s
      retries: 3

networks:
  frontend:
    driver: bridge
    attachable: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35