插件窝 干货文章 Docke如何部署nginx并配置

Docke如何部署nginx并配置

Nginx Docker conf 配置 876    来源:    2025-04-22

Docker部署Nginx并配置指南

基础部署

1. 拉取Nginx镜像

docker pull nginx

2. 运行Nginx容器

docker run --name my-nginx -p 80:80 -d nginx
  • --name my-nginx: 为容器指定名称
  • -p 80:80: 将主机80端口映射到容器80端口
  • -d: 后台运行

自定义配置

1. 创建本地配置目录

mkdir -p ~/nginx/conf
mkdir -p ~/nginx/html
mkdir -p ~/nginx/logs

2. 复制默认配置到本地

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

3. 修改配置

编辑~/nginx/conf/nginx.conf~/nginx/conf/conf.d/default.conf文件

4. 运行带自定义配置的容器

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

常用配置示例

1. 静态网站配置

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;
    }
}

2. 反向代理配置

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部署

创建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
  • 查看Nginx日志: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

SSL配置

1. 准备SSL证书

将证书文件(.crt和.key)放入~/nginx/conf/ssl/目录

2. 配置HTTPS

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;
}

性能优化

1. 调整worker进程数

nginx.conf中:

worker_processes auto; # 自动根据CPU核心数设置
events {
    worker_connections 1024;
}

2. 启用Gzip压缩

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

通过以上步骤,你可以灵活地在Docker中部署和配置Nginx服务器。