思考:
制作出的镜像尺寸尽可能小
我们使用基于alpine的nginx镜像可以满足需求,这里我们选取nginx:1.23.2-alpine作为上游基础镜像
运行时用户应该已非root用户运行
这里nginx基础镜像已经添加普通用户,此步骤可以忽略
设置时区,方便排查问题
这里通过设置环境变量 TZ=Asia/Shanghai来处理
nginx配置需要适配vue项目规则
这里需要在默认的http block添加 try_files uri/ /index.html,否则项目无法正常访问
可以对nginx静态资源进行一些优化
我们主要对项目中可能存在的html,css,js等进行压缩处理.
步骤:
- 拉取nginx上游基础镜像
docker pull nginx:1.23.2-alpine
- 从基础镜像中拷贝默认配置
docker run --rm nginx:1.23.2-alpine /bin/cat /etc/nginx/conf.d/default.conf > default.conf
- 调整default.conf配置
server {
listen 80;
server_name localhost;
#开启访问日志
access_log /var/log/nginx/host.access.log main;
location / {
#对静态资源开启压缩
gzip on;
gzip_static on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 5;
gzip_types text/plain application/json application/javascript application/x-javascript text/css application/xml text/javascript;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
#可以在这里设置浏览器缓存策略,进一步优化
# expires 24h;
root /usr/share/nginx/html;
index index.html index.htm;
#这里适配vue项目,不加无法访问.
try_files $uri $uri/ /index.html /index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
- 编写Dockerfile文件
FROM nginx:1.23.2-alpine
ENV TZ=Asia/Shanghai
COPY default.conf /etc/nginx/conf.d/default.conf
- 完成制作镜像
docker build -t fakerepo/vue-nginx:20221106 .
- 使用时我们把项目包add到/usr/share/nginx/html即可
参考:
docker的nginx镜像 hub.docker.com/_/nginx
nginx的资料和参数配置 nginx.org/en/