웹프로그래밍 : Nginx와 Docker를 이용한 프로젝트 구성

chanyeong yu ·2025년 3월 26일

웹프로그래밍

목록 보기
3/12

Nginx와 Docker를 이용한 프로젝트 구성

1. 프로젝트 개요

  • Frontend (React Vite): 정적 파일(index.html, style.css, script.js)을 Nginx를 통해 제공.
  • Backend (Express): /dweb 경로에서 API 요청을 처리.
  • Nginx 역할:
    • React 빌드 파일을 제공.
    • /dweb 경로 요청을 Express 서버로 프록시 전달.

2. 프로젝트 디렉토리 구조

project/
├── frontend/
│   ├── src/   # React 소스 코드
│   ├── package.json
│   ├── vite.config.js
├── proxy/
│   ├── static/ 
│	     │── dist/  # React 빌드 결과물, 옮겨준다 
│   ├── nginx.conf
│   └── Dockerfile
├── vercel_serverless
│   ├── api
│   	├── chat.js
└── docker-compose.yml

3. React Vite 프론트엔드 설정

1) React 프로젝트 생성 및 빌드

React 애플리케이션을 생성하고 빌드합니다.

React 프로젝트 생성

cd frontend
npm create vite@latest .
npm install

React 빌드 실행

npm i 
npm run build  # dist 폴더 생성

다음 명령어가 성공적으로 실행되면 dist 폴더가 생성된다.


4. Express 백엔드 설정

1) Express 서버 코드 작성]

  • server 디렉토리를 만든다.

  • server/server.js 파일 작성:

const express = require("express");
const app = express();

let count = 0;

app.get("/dweb", (req, res) => {
    count += 1;
    res.json({ num: count });
});

app.listen(3000, () => {
    console.log("Server is running on port 3000");
});

2) 의존성 설치

cd server
npm init -y  # 기본 package.json 생성
npm install express  # Express 설치

5. Nginx 설정

1) Nginx 설정 파일 작성

proxy/nginx.conf 파일 작성:

http {
    include mime.types;

    upstream backend {
        server express-server:3000;  # Express 컨테이너 이름과 포트
    }

    server {
        listen 80;  # Nginx 컨테이너 내부 포트

        root /usr/share/nginx/html;  # React 빌드 결과물 경로

        location / {
            index index.html;
            try_files $uri $uri/ =404;
        }

        location /dweb {
            proxy_pass http://backend;  # Express 서버로 프록시 전달
        }
    }
}

events {}

6. Docker Compose 설정

1) Docker Compose 파일 작성

docker-compose.yml 파일 작성:

version: '3.8'

services:
  express:
    build:
      context: ./server
      dockerfile: Dockerfile
    container_name: express-server
    ports:
      - "3000:3000"
    networks:
      - dweb-network

  nginx:
    build:
      context: ./proxy
      dockerfile: Dockerfile
    container_name: nginx-proxy
    ports:
      - "8080:80"
    depends_on:
      - express
    networks:
      - dweb-network

networks:
  dweb-network:
    driver: bridge

2) Dockerfile 작성

Proxy Dockerfile (proxy/Dockerfile):

FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf
COPY ../frontend/dist /usr/share/nginx/html/
# 근데 여기서 오류가 생길 수 있다. 
# proxy 디렉토리에서 frontend를 접근하지 못할 수 있다.

# 필요시 frontend/에서 생성된 dist 디렉토리를 nginx로 이동,
## COPY static/dist /usr/share/nginx/html/로 수정 

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

Server Dockerfile (server/Dockerfile):

FROM node:16-alpine

WORKDIR /usr/src/app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 3000

CMD ["node", "server.js"]

7. 실행 및 테스트

dist 파일 생성

npm run build

컨테이너 빌드 및 실행

docker-compose up -d --build

컨테이너 상태 확인

docker ps

컨테이너 다운

docker compose down --rmi all -v

브라우저 테스트

0개의 댓글