文章目录
- 导语
- 传统方式
- 1、下载镜像
- 2、copy项目文件到docker中
- 3、访问
- 打包镜像的方式
- 1、创建 Dockerfile
- 2、创建 Nginx 配置文件
- 3、构建 Docker 镜像
- 4、运行 Docker 容器
- 5、访问前端项目
- 总结
导语
这篇博客将介绍 docker 使用 nginx 部署前端项目的两种方式
传统方式
1、下载镜像
docker pull nginx
2、copy项目文件到docker中
这里先介绍几个关键的路径和配置:
# 默认的配置文件路径
/etc/nginx/nginx.conf
# 一般上面的nginx.conf会引入conf.d/*.conf,所以conf.d目录下的文件都能生效
/etc/nginx/conf.d/default.conf
# 这个是默认的default.conf的项目路径,如下
/usr/share/nginx/html
default.conf
server {listen 80;listen [::]:80;server_name localhost;#access_log /var/log/nginx/host.access.log main;location / {root /usr/share/nginx/html;index 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;#}
}
以上我们知道,将项目放到 /usr/share/nginx/html/
下就能使用 default.conf 配置了,我们将前端项目假设叫 index.html 复制到改目录下:
cd index.html所在的目录
docker cp index.html mynginx:/usr/share/nginx/html/
3、访问
127.0.0.1:80
上面配置的是80端口,也可以修改
打包镜像的方式
我们可以将以上所有的操作打包成一个镜像,只需运行镜像就能访问项目,而不需要上面的1/2/3步,这也是 docker 的正确使用方式,这样打包成一个镜像后,你的整个应用(前端项目和 Nginx)变得自包含,依赖关系清晰,更易于移植和部署。
1、创建 Dockerfile
在你的前端项目根目录下创建一个名为 Dockerfile 的文件,用于定义 Docker 镜像的构建过程。
# 使用 Nginx 作为基础镜像
FROM nginx:latest# 删除默认 Nginx 配置文件
RUN rm -rf /etc/nginx/conf.d/default.conf# 将本地的 Nginx 配置文件复制到容器中
COPY nginx.conf /etc/nginx/conf.d/# 将前端项目的静态文件复制到 Nginx 的默认发布目录
COPY dist /usr/share/nginx/html# 暴露 Nginx 的默认 HTTP 端口
EXPOSE 80# 启动 Nginx
CMD ["nginx", "-g", "daemon off;"]
2、创建 Nginx 配置文件
在同一目录下创建一个名为 nginx.conf 的 Nginx 配置文件,用于配置 Nginx 服务器。
server {listen 80;location / {root /usr/share/nginx/html;index index.html;try_files $uri $uri/ /index.html;}# 可以根据需要添加其他配置项
}
3、构建 Docker 镜像
在包含 Dockerfile 和 nginx.conf 文件的目录下,执行以下命令构建 Docker 镜像:
docker build -t your-frontend-image .
4、运行 Docker 容器
使用以下命令在 Docker 容器中运行你的前端项目:
docker run -p 8080:80 --name your-frontend-container -d your-frontend-image
这将映射宿主机的 8080 端口到容器的 80 端口,并在后台运行容器。
5、访问前端项目
现在,你可以通过访问 http://localhost:8080 来查看部署在 Docker 中的前端项目。
注意:上述步骤假设你的前端项目构建后的文件位于 dist 目录中。确保根据你的实际项目结构和构建输出调整 Dockerfile 中的路径和文件名。
总结
但是据我所知,前端项目一般不会像这样打包成镜像,因为前端对 nginx 没有那么的依赖,比如,两个人同时开发一个项目,基本就是 node 版本的不同可能会导致环境不同,但是最终都是打包成 dist 静态文件部署到 nginx 上,所以没必要把 nginx 和项目捆绑在一起。
所以,我遇到的前端项目基本就是服务器直接安装 nginx,并不使用 docker,当然用 docker 维护一个Nginx也是不错的选择。
而后端就不一样了,比如 java,本地要依赖 jdk 的版本,服务器也要依赖 jdk 的版本,所以后端更适合将 jdk 这种依赖和项目打包成一个镜像进行发布,这样就不会有环境不一致的问题了。