nginx部署前端项目(linux、docker)

发布于:2025-03-29 ⋅ 阅读:(29) ⋅ 点赞:(0)

引言

CentOS 7系统上使用docker安装nginx,使用nginx部署一个由Vue开发、打包的项目

docker安装nginx

这里不多赘述,直接上docker-compose.yml代码

 nginx:
   container_name: nginx
   image: nginx:1.27.2
   ports:
     - "80:80"
   volumes:
     - /docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
     - /docker/nginx/conf/conf.d:/etc/nginx/conf.d
     - /docker/nginx/html/dist:/etc/nginx/html
     - /docker/nginx/logs:/var/log/nginx
   networks:
     - myNetwork

需要注意的是容器卷里的/docker/nginx/html/dist,到时候部署前端项目时把dist文件夹直接放到/nginx/html文件夹里就行

nginx部署

前端打包的dist文件夹直接放到/nginx/html目录里
然后看nginx.conf的代码

# 此处注意用户不能是别的, 否则会报403错误
user  root;
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;


    server {
	    listen       80;
	    listen  [::]:80;
	    server_name  localhost;
	    
	    location / {
	    	#此处路径对应nginx容器内的/etc/nginx/html,所以需要将容器卷dist挂载到容器内的html
	        root html;
	        index index.html index.htm;
	    }
	
	}
}

常见问题

404: 可能是容器内的项目文件夹html为空, 可能是容器卷挂载错误
403: 禁止访问index.html,两种情况:1.可能是容器内的项目文件夹html不存在index.html,可能是容器卷挂载错误;2.可能是权限问题,需要将nginx.conf开头的用户改为root: user root
500:需要自行排查

查看日志的两种方式

docker logs nginx
cat /nginx/logs/error.log