跳至主要內容

Docker 安装 Nginx

bsfc.tech大约 1 分钟DockerNginx

Docker 安装 Nginx

1. 获取 SSL 证书和私钥

首先,你需要一个 SSL 证书和一个私钥。你可以从证书颁发机构(CA)购买,或者使用免费的证书服务,如 Let's Encrypt。

2. 准备 Nginx 配置文件

创建一个 Nginx 配置文件,其中包含你的 SSL 证书和私钥的路径。以下是一个简单的示例:

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;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon;
    gzip_min_length 128;

    #include /etc/nginx/conf.d/*.conf;
	
	server {
		listen       80;
		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 443 ssl;
		server_name bsfc.tech;

		location / {
			proxy_set_header HOST $host;
			proxy_set_header X-Forwarded-Proto $scheme;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_pass http://bsfc.tech;
		}

		## SSL证书
		ssl_certificate /etc/nginx/cert/bsfc.tech.pem;
		ssl_certificate_key /etc/nginx/cert/bsfc.tech.key;
		ssl_session_timeout 5m;

		# SSL/TLS协议配置
		ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
		ssl_prefer_server_ciphers on;
	}
}

3. 运行容器Nginx

现在可以运行你的Docker容器,开启对应的端口和挂载的目录:

docker run --name nginx -d -p 80:80 -p 443:443 \
-v /data/nginx_conf/nginx.conf:/etc/nginx/nginx.conf \
-v /data/nginx/www:/usr/share/nginx/html \
-v /data/nginx/logs:/var/log/nginx \
-v /data/nginx/conf:/etc/nginx/ \
nginx:1.25.4

4. 配置防火墙

确保你的服务器防火墙允许 80 443 端口的流量,并将你的域名解析到服务器的 IP 地址。


以上是本篇文章的全部内容,如对你有帮助帮忙点赞 + 转发 + 收藏。