DEV Community

Perm Chao
Perm Chao

Posted on • Edited on

2 1

Basic config nginx with static CRA files in container

การตั้งค่า Dockerfile กับ React เบื้องต้น

โครงสร้างโปรเจค

  • src/
  • production.Dockerfile
  • nginx.conf
  • package.json

ขั้นตอน

1) เตรียมไฟล์ nginx

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;
 }
}
Enter fullscreen mode Exit fullscreen mode

2) เขียน Dockerfile ตามนี้

# --- ขั้นตอนการ build ไฟล์ให้ออกมาเป็น static files ---
FROM node:alpine as builder
# เพื่อให้เข้าถึงไฟล์ build ง่ายๆ ให้เก็บไฟล์ไว้ในโฟรเดอร์ที่เข้าถึงง่าย ๆ
WORKDIR /app
COPY . /app
# เพื่อให้สั่งทำงานบางคำสั่งได้โดยตรงเช่นพวก webpack, carco, etc
ENV PATH /app/node_modules/.bin:$PATH
# ลง packages ต่างๆ ใน package.json
RUN yarn
# สั่งสร้างไฟล์ static files
RUN yarn build

# --- ขั้นตอนการตั้งค่า nginx ---
FROM nginx:alpine
# คัดลอกไฟล์มาจาก container ที่แล้ว
COPY --from=builder /app/build /usr/share/nginx/html
# ใส่ nginx config ที่เราตั้งเอง
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d
EXPOSE 80
# Run nginx บน foreground
CMD ["nginx", "-g", "daemon off;"]
Enter fullscreen mode Exit fullscreen mode

3) สั่ง build ไฟล์

docker build \
-t my-react-app:v1.0 \
-f production.Dockerfile \
.
Enter fullscreen mode Exit fullscreen mode

4) ลอง run

docker run -p 80:80 -t my-react-app:v1.0
Enter fullscreen mode Exit fullscreen mode

ขอขอบคุณแหล่งที่มา https://medium.com/swlh/dockerizing-a-react-application-with-docker-and-nginx-19e88ef8e99a

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs