# Docker-compose构建nginx和acme.sh并自动续期证书

本文前提:已经绑定了Cloudflare API Key

# 0x00 构建工作目录

workdir
  - compose
    -- acme
      --- acme.sh 
      *** Dockerfile
    -- nginx
      --- conf
        **** my.domain.com.conf
      --- log
      *** Dockerfile
  - wwwroot
    -- my.domain.com
      *** index.html
  * docker-compose.yml

# 约定:
#     - 表示目录
#     * 表示文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 0x01 编写nginx的Dockerfile

FROM nginx:1.17.5

COPY ./compose/nginx/conf/my.domain.com.conf /etc/nginx/conf.d/
COPY ./compose/acme/acme.sh/my.domain.com/fullchain.cer /etc/letsencrypt/my.domain.com/
COPY ./compose/acme/acme.sh/my.domain.com/my.domain.com.key /etc/letsencrypt/my.domain.com/
1
2
3
4
5

# 0x02 编写acme.sh的Dockerfile

FROM neilpang/acme.sh

1
2

# 0x03 编写docker-compose.yml

version: "3"

services:
  acme.sh:
    build:
      context: .
      dockerfile: ./compose/acme/Dockerfile
    container_name: acme
    volumes:
        - "./compose/acme/acme.sh:/acme.sh:z"
    command: 
        # 首次部署需要进入该容器生成证书
        # acme.sh --issue --dns dns_cf -d www.my.domain.com -d my.domain.com
        # tail -F anything 保持容器运行
      - sh
      - -c
      - |
          acme.sh --issue --dns dns_cf -d my.domain.com
          tail -F anything 
 
##### 1. 首次运行时把 nginx 整个代码块都注释掉,
##### 2. 执行 docker-compose up --build,目的是首先获得域名ssl证书;
##### 3. 当成功获得域名证书后,再取消 nginx 代码块的注释

  nginx:
    build:
      context: .
      dockerfile: ./compose/nginx/Dockerfile
    container_name: nginx
    restart: always
    volumes:
      - ./wwwroot/my.domain.com/:/wwwroot/my.domain.com/
      - ./compose/nginx/log/:/var/log/nginx/:rw
    ports: 
      - "80:80"
      - "443:443"
    depends_on:
      - acme.sh

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
36
37
38
39

# 0x04 启动容器

docker-compose up --build

## 或者让容器后台运行

docker-compose up --build -d
1
2
3
4
5
上次更新:: 11/15/2020, 6:45:36 AM