目录
一、拉取nginx镜像
docker pull nginx
二、在宿主机中创建挂载目录
mkdir -p /data/nginx/{conf,conf.d,html,log}
三、将配置文件放到挂载目录
在/data/nginx/conf目录下放入nginx.conf文件,内容如下:
# 工作进程的数量
worker_processes auto;
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 D:/Program Files/nginx-1.23.3/access.log access; # 日志输出目录
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# include /etc/nginx/conf.d/*.conf;
# include /etc/nginx/sites-enabled/*;
# 链接超时时间,自动断开
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Headers Origin,Accept,Authorization,platformId,ut,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
add_header Access-Control-Allow-Credentials true;
proxy_connect_timeout 5;
proxy_read_timeout 60;
proxy_send_timeout 5;
proxy_buffer_size 16k;
proxy_buffers 4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
charset utf-8;
# 开启gzip 压缩
gzip on;
# 设置gzip所需的http协议最低版本 (HTTP/1.1, HTTP/1.0)
gzip_http_version 1.1;
# 设置压缩级别,压缩级别越高压缩时间越长 (1-9)
gzip_comp_level 4;
# 设置压缩的最小字节数, 页面Content-Length获取
gzip_min_length 1000;
gzip_buffers 4 8k;
gzip_vary on;
# 设置压缩文件的类型 (text/html)
gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/jpg image/gif image/png image/x-ms-bmp;
gzip_disable "MSIE [1-6]\.";
location / {
proxy_redirect off;
proxy_set_header Host $host; # 传递域名
proxy_set_header X-Real-IP $remote_addr; # 传递ip
proxy_set_header X-Scheme $scheme; # 传递协议
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
root /usr/share/nginx/html; # 访问根目录
index index.html index.htm;
}
}
}
/data/nginx/html目录下放入需要访问的网站内容。
四、创建容器并启动
docker run \
--name=devNginx \
-d -p 80:80 \
-v /data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /data/nginx/log:/var/log/nginx \
-v /data/nginx/html:/usr/share/nginx/html \
nginx
第一个-v:挂载nginx的主配置文件,以方便在宿主机上直接修改容器的配置文件
第二个-v:挂载容器内nginx的日志,容器运行起来之后,可以直接在宿主机的这个目录中查看nginx日志
第三个-v:挂载静态页面目录
五、总结
通过 docker ps查看nginx是否正常运行。安装启动都没有问题之后,想着如何设置容器跟随系统自启动,这样就省去了手动操作。命令如下,详细内容下篇文章在做记录。
docker update --restart=always/no