如何在Docker中用nginx服务React应用程序

137 阅读3分钟

让我们在React中创建一个静态网站,并学习如何使用nginx在Docker容器中为其服务。为了简单起见,我们将使用标准的React应用程序,当你使用create-react-app 。我将使用yarn ,但也可以随意使用npm

我们将这个应用命名为react-nginx

yarn create react-app react-nginx

导航到新的应用程序文件夹。

cd react-nginx

现在我们知道我们需要几个文件来使用Docker:一个Dockerfile 和一个.dockerignore 文件。现在让我们来制作它们。

touch Dockerfile

对于我们的.dockerignore 文件,让我们把node_modules 扔在那里,然后就可以了。

echo "node_modules" > .dockerignore

构建Docker文件

是时候建立Docker文件了!我们有很多方法可以做到这一点,但今天我们将使用一个多阶段的过程。

  • 阶段1:用于构建前端资产的Node镜像
  • 阶段2:nginx阶段,为前端资产提供服务

第一阶段:构建前端资产

我们的第一个阶段将

  • 使用一个节点镜像
  • 将我们所有的React文件复制到工作目录中
  • 用yarn安装项目的依赖性
  • 用yarn构建应用程序

这就是Docker中的样子!

# Name the node stage "builder"
FROM node:10 AS builder
# Set working directory
WORKDIR /app
# Copy all files from current directory to working dir in image
COPY . .
# install node modules and build assets
RUN yarn install && yarn build

接下来,我们实际上是在为我们刚刚建立的内容提供服务!

第二阶段:我们的nginx服务器

我们的第二个阶段将。

  • 使用一个nginx镜像
  • 从nginx镜像中删除任何默认的静态资产
  • 从我们在第一阶段创建的builder 镜像中复制我们的静态资产
  • 为我们的容器指定运行nginx的入口。

下面是这个阶段在Docker文件中的样子。

# nginx state for serving content
FROM nginx:alpine
# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static assets
RUN rm -rf ./*
# Copy static assets from builder stage
COPY --from=builder /app/build .
# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]

棒极了让我们把这一切放在一起,实际运行我们的应用程序。

把它放在一起

我们的多阶段Docker文件现在看起来应该是这样的。

# Multi-stage
# 1) Node image for building frontend assets
# 2) nginx stage to serve frontend assets

# Name the node stage "builder"
FROM node:10 AS builder
# Set working directory
WORKDIR /app
# Copy all files from current directory to working dir in image
COPY . .
# install node modules and build assets
RUN yarn install && yarn build

# nginx state for serving content
FROM nginx:alpine
# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static assets
RUN rm -rf ./*
# Copy static assets from builder stage
COPY --from=builder /app/build .
# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]

现在我们已经组装好了我们的Docker文件,让我们建立一个名为react-nginx 的镜像。

docker build -t react-nginx .

现在我们的镜像已经建成,我们可以用下面的命令启动一个容器,它将在8080端口为我们的应用程序提供服务。

docker run --rm -it -p 8080:80 react-nginx

导航到http://localhost:8080,你现在应该可以看到我们的默认应用程序了。