“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Hello, I’m Shanyue.

The biggest benefit of deploying a docker front-end is to isolate the environment and manage it separately:

  1. The front-end project relies on Node V16, and the host cannot meet the dependency, so containers are used to meet the requirements
  2. The front-end project relies on NPM V8, and the host machine can’t meet the dependencies and uses containers to meet the requirements
  3. Front-end projects need to expose port 8080, which is easy to conflict with other services of the host. Container and service discovery are used to meet the needs

Deploy the front end using Docker

Assuming a front-end project runs locally, the following steps are required and the service is finally accessible at localhost:8080.

$ npm i
$ npm run build
$ npm start
Copy the code

So deploying the front end in Docker is roughly the same as how you would run a project locally, with a Dockerfile as follows

# Specify a node version number that satisfies the host environment
FROM node:16-alpine

Add the code to the working directory
WORKDIR /code
ADD . /code

# How to run a project
RUN npm install
RUN npm run build
RUN npm start

# Expose the port number of the outbound line, which can be discovered by external access services
EXPOSE 8080
Copy the code

Congratulations, you can write the above Dockerfile, which shows that you have a good understanding of Docker. But there are still a few issues, and we went through a wave of optimization

  1. usenode:16The base image is too extravagant and bulky, and the end product (JS/CSS/HTML) doesn’t need to rely on it. You can use smaller Nginx images for multi-phase builds.
  2. Multiple RUN commands are not conducive to hierarchical storage of Docker images.Can be combined into a RUN command
  3. Every timenpm i, Docker cache can be reasonably used. Changes in the contents of ADD command will destroy the cache. Package. json can be moved to the destination directory ahead of time, as long aspackage.json/lockfileThere will be no changenpm i

The optimized Dockerfile is as follows:

FROM node:16-alpine as builder

WORKDIR /code

ADD package.json package-lock.json /code
RUN npm install

ADD . /code

RUN npm run build 

# Select a smaller volume base image
FROM nginx:alpine

# Move build artifacts to nginx
COPY --from=builder code/build/ /usr/share/nginx/html/
Copy the code

What’s your answer to this question? Leave a comment!