外观
Docker安装
约 679 字大约 2 分钟
2025-09-07
基于Docker Compose
安装Nginx
服务,管理更方便。
创建项目工作目录
在一个合适的位置创建一个目录用于存放nginx
项目的数据,如:
mkdir /opt/nginx
创建docker-compose.yaml
在项目根目录下创建docker-compose.yaml
文件,内容如下
docker-compose.yaml
services:
nginx:
image: nginx:1.28.0-alpine3.21
container_name: nginx
restart: always
ports:
- "80:80"
- "443:443" # 需要https访问的可开启443端口
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf # 主配置
- ./conf.d:/etc/nginx/conf.d # HTTP配置
- ./tcp.d:/etc/nginx/tcp.d # TCP配置
- ./certs:/etc/ssl/certs # SSL证书
- ./html:/usr/share/nginx/html # 静态页面
- ./logs:/var/log/nginx # 日志
healthcheck: # 健康检查
test: ["CMD", "wget", "--spider", "-q", "http://localhost/health"]
interval: 30s
timeout: 10s
retries: 3
logging: # 日志限制
driver: "json-file"
options:
max-size: "10m" # 单个日志文件最大10MB
max-file: "30" # 保留30个历史日志文件
deploy: # 资源限制
resources:
limits:
cpus: "0.5" # 最多使用0.5个CPU核心
memory: 512M # 内存上限512MB
当前目录结构应当如下:
opt
nginx
docker-compose.yaml
配置Nginx
在项目根目录下创建以下文件,文件内容参考下方:
nginx.conf
:主配置文件conf.d/default.conf
:默认服务配置文件,含健康检查路径html/index.html
:主页面文件html/50x.html
:错误页面文件
nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
# http服务配置块
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;
keepalive_timeout 65;
gzip on;
include /etc/nginx/conf.d/*.conf; # 包含conf.d目录下所有.conf结尾的文件内容
}
# TCP服务配置块
stream {
include /etc/nginx/tcp.d/*.conf; # 包含tcp.d目录下所有.conf结尾的文件内容
}
conf.d/default.conf
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# 健康检查端点
location /health {
access_log off;
return 200 "OK";
add_header Content-Type text/plain;
}
}
html/index.html
<h1>Welcome to Nginx!</h1>
html/50x.html
<h1>500! Error!</h1>
检查目录结构是否正确,当前目录结构应当如下:
opt
nginx
conf.d
default.conf
html
index.html
50x.html
nginx.conf
docker-compose.yaml
启动Nginx
由于我们使用了volumes
挂载主机的目录,MacOS
上需要在Docker for Mac
客户端上添加目录权限。设置路径为Settings->Resources->File Sharing
,在Virtual file shares
中添加你的项目根目录。
确保项目目录权限后,在项目根目录下运行以下命令启动Nginx
容器:
% docker-compose up -d
[+] Running 2/2
✔ Network nginx_default Created 0.0s
✔ Container nginx Started 0.1s
初始化过程中,依据我们配置的目录挂载规则,会在根目录创建一些目录,初始化后目录结构如下:
opt
nginx
certs
…
conf.d
default.conf
html
index.html
50x.html
logs
access.log
error.log
tcp.d
…
nginx.conf
docker-compose.yaml
待完全启动成功后,可在目标主机上访问http://localhost,看到Welcome to Nginx!
文字即代表成功。