容器部署Vue项目"/>
Nginx容器部署Vue项目
简介
首先需要准备:
1.Nginx镜像
2.已打包好的Vue项目
Vue打包命令:
npm run build
运行容器
将Nginx镜像运行成容器(该命令在后续操作做完之后再敲)
docker run -it --name nginx --hostname=nginx --privileged=true -u root --restart=always -v /home/vue_pack:/home/nginx -v /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -p 80:80 -d nginx
这里将Nginx容器里面的目录映射到了宿主机上,因为容器里面没有vi指令,导致后续无法需要修改配置文件,所以选择映射到宿主机上操作,映射的目录如下(前者是宿主机的目录):
1.vue_pack目录用于存放已打包vue项目的dist文件
/home/vue_pack:/home/nginx
2.将nginx容器中的nginx.conf 配置文件映射到宿主机上的nginx.conf中
/home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
第二步的映射需要提前在宿主机上创建nginx.conf文件,否则会报错,创建命令如下
cd /home # 进入home目录
mkdir nginx # 在/home目录下创建nginx目录
cd nginx # 进入nginx目录
mkdir conf # 在nginx目录下创建conf目录
touch nginx.conf # 创建nginx.conf文件
配置文件修改以及存放打包代码
进入Vue项目目录将dist文件夹复制一份存到映射出来的code目录下
cp -r dist /home/vue_pack/
运行完该命令后,此时容器中/home/nginx路径下也会有一个dist目录
接下来只需要修改nginx的配置文件,然后重新运行容器即可完成部署
进入/home/nginx/conf/目录下,打开nginx.conf文件
cd /home/nginx/conf/
vi nginx.conf
nginx.conf配置如下:
user nginx;
worker_processes 4;error_log /var/log/nginx/error.log warn;
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;#include /etc/nginx/conf.d/*.conf;underscores_in_headers on;client_max_body_size 1024m;server {listen 80;listen [::]:80;server_name _;# 项目目录root /home/nginx/dist;# Load configuration files for the default server block.#include /etc/nginx/default.d/*.conf;location / {root /home/nginx/dist;index index.html index.htm;try_files $uri $uri/ /index.html;}error_page 404 /404.html;location = /404.html {}error_page 500 502 503 504 /50x.html;location = /50x.html {}}
}
配置文件中重要的是http代码块和其中的server代码块,下面介绍一下具体的代码作用
这里需要注释一下代码
#include /etc/nginx/conf.d/*.conf;
具体的原因后面学习后补充,如果不注释的话,只能看见nginx的欢迎页面
其次就是指定项目目录,也就是打包好的dist文件夹路径,容器中存放代码的位置是 /home/nginx/dist
root /home/nginx/dist;
还需要注意location代码块中必须加入try_files $uri $uri/ /index.html;
try_files $uri $uri/ /index.html;
这样可以避免刷新页面的时候出现404报错
最后重启容器即可
docker restart nginx #这里跟容器名字或者容器ID都可
总结
以上便是如何使用Nginx容器部署Vue项目的具体方法,简单来讲就是将容器的目录映射到宿主机上,然后在宿主机上存入代码,修改配置文件,重启容器便可完成部署
更多推荐
Nginx容器部署Vue项目
发布评论