← Back to archive
Programming Notes

After npm run build, Serve as HTTP with Alpine and nginx in Docker

配置部署

To implement a simple CI setup that automatically builds and deploys to a target server after code commits, after deploying Gitea and Jenkins you still need further steps.

With Node.js, after npm run build you get pure HTML in the dist directory. Using npm install http-server -g yields a Docker image as large as 100M, so switch to Alpine with nginx for deployment—size drops to about 13M.

mkdir project
cd project
mkdir app
mkdir nginx

Put all Node.js project files under app, then create a file default.conf in the nginx directory.

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        location / {
                root /app;
                index index.html;
        }
}

Then create a Dockerfile in the project directory:

FROM node:12.6.0-buster-slim AS build
ENV PROJECT_ENV production
EXPOSE 80

WORKDIR /app
COPY ./app/ ./
RUN npm config set registry http://registry.npm.taobao.org/
RUN npm install yarn -g
RUN yarn config set registry https://registry.npm.taobao.org/
RUN yarn
RUN npm run build:prod 
COPY ./nginx /nginx

FROM alpine
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN apk add nginx
COPY --from=build /nginx /etc/nginx/conf.d
COPY --from=build /app/dist /app
ENTRYPOINT ["nginx","-g","pid /tmp/nginx.pid; daemon off;"]

In Jenkins, after configuring git checkout, create a deployment script:

docker stop wm || true && docker rm wm || true
docker build -t wm_image .
docker run -d -p 80:80 --restart=always --name wm wm_image

Written by Master Sanfu on April 23, 2021. Please credit the source if you share.

Translation Notice: This English version was translated with AI assistance. Specialized, historical, religious, or culturally sensitive terms may contain nuances, inaccuracies, or debatable wording. In case of ambiguity or discrepancy, the original Chinese text shall prevail.