使用 Docker 将 ReactJS、NodeJS 和 NGINX 容器化
让我们将应用程序容器化
后续步骤
安装 Docker 和 Docker Compose
在开始项目之前,请安装 Docker 和 Docker-compose。您可以从这里
安装。
创建 React 应用
现在,让我们使用 create-react-app 创建一个简单的 React 应用。
npm install -g create-react-app
create-react-app react-docker-demo-app
让我们将应用程序容器化
添加 Dockerfile
在项目目录的根目录下创建一个名为 Dockerfile 的文件。
FROM node:10-alpine as builder
# install and cache app dependencies
COPY package.json package-lock.json ./
RUN npm install --only=prod&& mkdir /react-frontend && mv ./node_modules ./react-frontend
WORKDIR /react-frontend
COPY . .
RUN npm run build
第一阶段是使用 Node 构建应用程序。这里我们使用的是 Alpine 版本,因为它是最轻量级的版本。
构建过程会生成一个包含代码块文件的构建目录。
添加 .dockerignore
创建一个.dockerignore文件,并将node_modules目录添加到其中。
node_modules
这将加快镜像构建过程,因为我们的本地依赖项将不会发送到 Docker 守护程序。
现在开始构建 Docker 镜像。
docker build -t react-frontend .
然后,使用我们刚刚创建的镜像运行容器。
docker run -p 3000:3000 react-frontend
在浏览器中打开http://localhost:3000,你应该就能看到 React 应用的主页了。
生产环境构建
添加 NGINX 服务器
NGINX 充当反向代理,就像一个中间人,连接向该代理发出请求的客户端和向该代理发出请求并从其他服务器检索结果的代理。
要将 nginx 添加为应用程序的服务器,我们需要在项目根文件夹中创建一个 nginx.conf 文件。
nginx.conf
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
然后,将以下几行添加到 Dockerfile 中。
FROM nginx:1.16.0-alpine
COPY --from=builder /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
在这里,我们将上一步中的构建复制并粘贴到 nginx 文件夹中,并暴露端口 80 - 这将是容器监听连接的端口。
这样就能生成可用于生产的图像。
最后,整个 Dockerfile 应该如下所示:
FROM node:10-alpine as builder
# install and cache app dependencies
COPY package.json package-lock.json ./
RUN npm install && mkdir /react-frontend && mv ./node_modules ./react-frontend
WORKDIR /react-frontend
COPY . .
RUN npm run build
# ------------------------------------------------------
# Production Build
# ------------------------------------------------------
FROM nginx:1.16.0-alpine
COPY --from=builder /react-frontend/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
docker-compose.yml
Docker Compose 是一个用于从单个服务运行多个容器的工具。它使用一个 YAML 文件,其中包含运行容器所需的配置。
version: '3.7'
services:
react-frontend:
container_name: react-frontend
build:
context: .
dockerfile: Dockerfile
volumes:
- '.:/app'
- '/app/node_modules'
ports:
- '3000:3000'
environment:
- NODE_ENV=development
启动容器
docker-compose up
阻止集装箱
docker-compose down
后续步骤
这样一来,你就可以将 React 添加到更大的 Docker 项目中,用于开发和生产环境。
文章来源:https://dev.to/subhransu/nevertheless-subhransu-maharana-coded-5eam