Page cover

ReactJs

Dockerize ReactJs Application

Menyiapkan Project

Clone react application yang akan di deploy dan masuk ke dalam directory tersebut. Jika belum ada, buat project terlebih dahulu. Dokumentasi menyiapkan framework reactjs ada disini: ReactJs

Menyiapkan File Docker

Siapkan beberapa file docker yang diperlukan

File
Deskripsi

file konfigurasi dari nginx

berisi file konfigurasi dari docker

list file dan directory yang diabaikan

mendefinisikan dan menjalankan aplikasi multi-kontainer Docker

nginx.conf

Buat directory .config terlebih dahulu, kemudian buat file nginx.conf didalam folder tersebut

nginx.conf
server {
    listen 5000;
    server_name localhost;

    location / {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

Dockerfile

Pada directory utama, buat file Dockerfile

Dockerfile
# Use an official Node.js runtime as the build environment
FROM node:18-alpine as build

# Set the working directory in the container
WORKDIR /app

# Copy package.json and package-lock.json to the container
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the application code to the container
COPY . .

# Build the React app for production
RUN npm run build

# Use an official Nginx runtime as the web server
FROM nginx:alpine

# Copy the built app from the previous stage to the Nginx web root
COPY --from=build /app/build /usr/share/nginx/html

# Set the working directory in the container
WORKDIR /usr/share/nginx/html

# Remove the default Nginx configuration
RUN rm -rf /etc/nginx/conf.d/*

# Create a custom Nginx configuration file
COPY .config/nginx.conf /etc/nginx/conf.d/default.conf

# Expose port 80 to the outside world
EXPOSE 5000

# Start Nginx server
CMD ["nginx", "-g", "daemon off;"]

.dockerignore

Pada directory utama, buat file .dockerignore

.dockerignore
.git
.gitignore
.dockerignore
Dockerfile
docker-compose.yml
package-lock.json

docker-compose.yml

Pada directory utama, buat file docker-compose.yml

docker-compose.yml
version: '3'
services:
  webapp:
    build: .
    image: react-deploy
    container_name: react-deploy
    ports:
      - "5000:5000"

Menjalankan Container

Build image dan jalankan container

docker compose up -d --build

Seharusnya aplikasi sudah bisa berjalan, buka browser dan akses IP server dengan port 5000 (http://127.0.0.1:5000). Untuk menggunakan port lain, ganti setiap port pada file nginx.conf, Dockerfile, dan docker-compose.yml

tampilan pada browser

Referensi

github.com
ikantongkol.gitbook.io
www.digitalocean.com

Last updated