Deploying Nginx with Docker

Richard Yang Lv2

用了Hexo一段时间,仅仅用于blog的文章功够用(废话) ,但想要网站更灵活更完善,最终还是得用Nginx这类软件来管理和建立网站。

挑选镜像

Nginx官方就提供了有镜像,所以不多思考,拿上官方的镜像直接用就行。

安装Nginx

依旧传统配方,先创建一个docker-compose.yaml文件:

docker-compose方便配置和重构,个人感觉

docker-compose.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
services:
nginx:
image: nginx
container_name: nginx
restart: always
volumes:
- "./nginx/conf/nginx.conf:/etc/nginx/nginx.conf"
- "./nginx/conf/conf.d:/etc/nginx/conf.d"
- "./nginx/data:/usr/share/nginx/data"
- "./nginx/html:/usr/share/nginx/html"
- "./nginx/log:/var/log/nginx"
environment:
TZ: Asia/Shanghai
LANG: en_US.UTF-8
network_mode: host

目录的映射(volumes)可以自定义,但是网络模式(network_mode)强烈建议host模式,不然后期改容器端口很麻烦。

接着使用cd命令到docker-compose.yaml文件所在目录下,运行以下命令。

1
docker compose up -d

使用以下命令,观察到nginx已经运行且访问本机地址能看到默认网页即可

1
docker ps

配置Nginx

配置文件的路径以宿主机的路径为例

首先简单更改./nginx/conf/nginx.conf下的配置,基本不动,开个gzip压缩加速数据传输就行

nginx.conf
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

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/conf/conf.d/default.conf,也就是上述文件最后include的文件。参考官方文档

default.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# HTTPS 主服务
server {
listen 443 ssl;
server_name localhost;

# 配置SSL证书,这里路径要用容器内的
ssl_certificate /usr/share/nginx/html/SSL/yremmmm.com.pem;
ssl_certificate_key /usr/share/nginx/html/SSL/yremmmm.com.key;

location / {
# 建议用 127.0.0.1 而非域名,避免 DNS 循环
# 端口代理的必须从30000开始,这是nginx要求的
proxy_pass http://127.0.0.1:30000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

# HTTP 强制跳转 HTTPS
server {
listen 80;
server_name localhost;
return 301 https://$host$request_uri;
}

当然,不用https直接用http也是可行的

default.conf
1
2
3
4
5
6
7
8
server {
listen 80;
server_name localhost;

location / {
proxy_pass http://127.0.0.1:30000;
}
}
  • Title: Deploying Nginx with Docker
  • Author: Richard Yang
  • Created at : 2023-03-04 11:23:56
  • Updated at : 2026-01-03 16:59:27
  • Link: http://www.yremmmm.com/2023/03/04/Deploying-Nginx-with-Docker/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Deploying Nginx with Docker