docker pull nginx
docker run --name my-nginx -p 80:80 -d nginx
--name my-nginx
: 为容器指定名称-p 80:80
: 将主机80端口映射到容器80端口-d
: 后台运行mkdir -p ~/nginx/conf
mkdir -p ~/nginx/html
mkdir -p ~/nginx/logs
docker run --name tmp-nginx -d nginx
docker cp tmp-nginx:/etc/nginx/nginx.conf ~/nginx/conf/
docker cp tmp-nginx:/etc/nginx/conf.d ~/nginx/conf/
docker rm -f tmp-nginx
编辑~/nginx/conf/nginx.conf
或~/nginx/conf/conf.d/default.conf
文件
docker run --name my-nginx \
-p 80:80 \
-v ~/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v ~/nginx/conf/conf.d:/etc/nginx/conf.d \
-v ~/nginx/html:/usr/share/nginx/html \
-v ~/nginx/logs:/var/log/nginx \
-d nginx
server {
listen 80;
server_name localhost;
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;
}
}
server {
listen 80;
server_name localhost;
location /api/ {
proxy_pass http://backend:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
创建docker-compose.yml
文件:
version: '3'
services:
nginx:
image: nginx
container_name: my-nginx
ports:
- "80:80"
- "443:443"
volumes:
- ~/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
- ~/nginx/conf/conf.d:/etc/nginx/conf.d
- ~/nginx/html:/usr/share/nginx/html
- ~/nginx/logs:/var/log/nginx
restart: unless-stopped
启动服务:
docker-compose up -d
docker ps
docker logs my-nginx
docker exec -it my-nginx bash
docker exec my-nginx nginx -s reload
docker stop my-nginx
docker start my-nginx
docker rm my-nginx
将证书文件(.crt和.key)放入~/nginx/conf/ssl/
目录
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# SSL配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
在nginx.conf
中:
worker_processes auto; # 自动根据CPU核心数设置
events {
worker_connections 1024;
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
通过以上步骤,你可以灵活地在Docker中部署和配置Nginx服务器。