ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Docker로 Nginx 정적 파일 서빙 & 리버스 프록시 설정
    MSA & 쿠버네티스(Kubernetes) - k8s 2023. 3. 4. 12:43
    728x90

    개요

    도커가 설치되어 있다고 가정되고 진행됩니다.

    도커에 대한 전반적인 지식이 조금 있다고 가정되고 진행됩니다.

     

    Docker Nginx 이미지 받기

    docker pull nginx

    정적파일 준비하기

     echo "<html><body>Hello, Local Index.html</body></html>" >> index.html

    파일이 저장된 경로 /Desktop/docker

     

    볼륨 옵션 주어 nginx 이미지 컨테이너로 생성

    docker run -d --name my_nginx -p 80:80 -v [your_computer_user_path]\Desktop\docker:/mycustome/path -it nginx

    볼륨 기능을 통해 컨테이너와 독립하여 데이터를 관리할 수 있습니다.

    컨테이너와 독립되는 호스트 PC(로컬 PC)의 저장공간에서 볼륨에 연결시켜 데이터 쓰기 작업을 진행합니다.

    이제 컨테이너를 삭제해도 호스트에 기록한 볼륨은 계속 남이 있을 수 있습니다.

     

    -v 옵션을 통하여 [나의 로컬PC 경로:연결할 도커 컨테이너의 경로]를 지정합니다

     

    볼륨이 매핑되었는지 확인

    docker exec -it my_nginx bash
    cd /mycustome/path/
    ls
    Dockerfile  docker-compose.yml  index.html
    • my_nginx 컨테이너의 bash에 접속합니다.
    • /mycustome/path/로 이동합니다.
    • ls 명령어로 해당 path에 파일들을 탐색합니다.
    • local pc에 존재했던 파일들이 잘 매핑된 것을 볼 수 있습니다.

    localhost로 접속

    이제 나의 index.html파일이 보일까요?

    그렇지 않습니다.

    nginx 컨테이너에 /mycustome/path 에 존재하는 index.html을 서빙하라고 알려주어야 합니다.

     

    Nginx Config 설정

    apt update
    apt install vim -y

    우선 my_nginx 컨테이너에 vi를 설치합니다. (설정 파일을 수정하기 위해서)

     

    nginx를 설치하면 기본적으로 /etc/nginx/confd./deafult.conf 파일이 존재하며 해당 파일에서 설정이 이루어집니다.

    rm /etc/nginx/conf.d/default.conf
    vi /etc/nginx/conf.d/default.conf

    파일 삭제후 다시 생성하는 명령어입니다.

     

    새롭게 생성한 /etc/nginx/conf.d/default/conf 파일

    server {
        listen 80;
    
        location / {
            root /home/jscode;
            index index.html;
            try_files $uri /index.html;
        }
    }

     

    • server가상 호스트 server_name의 url이 온다면 server 블록으로 이동
    • listen nginx 데몬 포트 정의
    • location 특정 url로 접근하면 어떤 rule를 따를 건지에 대한 구체적인 동작 정의
    • root nginx가 정적 서비스를 하는데 필요한 파일들이 어느 위치에 있는지 알려주는 지시자
    • index root 위치에서 어떤 파일을 기본 파일로 할껀지에 대한 지시자
    • try_files request에 대해서 어느 순서대로 처리해야할지에 대한 지시자

     

    명령어를 통하여 설정파일이 잘 동작하는지 확인

    nginx -t
    
    //결과
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful

     

    명령어를 통하여 nginx reload

    nginx -s reload
    
    //결과
    2023/03/03 17:35:42 [notice] 443#443: signal process started

    이제 localhost가 정상적으로 바뀌어서 적용됩니다.

    심지어 Local PC의 index.html 파일을 수정하면 my_nginx 컨테이너에 바로 적용되어 문구가 바뀌는 것을 확인할 수 있습니다.

     

    리버스 프록시로 front , backend 컨테이너 띄우기

    react(front), node(back) 프로젝트를 사용하여 해당 git repo를 참고하였습니다.

    https://github.com/wlsf82/frontend-and-backend

     

    GitHub - wlsf82/frontend-and-backend: Sample project with basic "backend" and frontend, running Cypress tests on GitHub Actions.

    Sample project with basic "backend" and frontend, running Cypress tests on GitHub Actions. - GitHub - wlsf82/frontend-and-backend: Sample project with basic "backend" and fronte...

    github.com

     

    다행히 노드가 설치되어 있음을 확인하였습니다.. 없으면 깔아야 합니다. (npm 명령어를 위해)

    node -v

     

    의존성 설치 후 build

    npm i //의존성 설치
    npm run build //react 빌드 -> 정적파일 떨어짐

    frontend 경로에 build파일이 생기고 static폴더가 생긴것을 확인할 수 있습니다.

     

    node 이미지 생성

    app-test.dockerfile

    FROM node:16-alpine
    
    WORKDIR /home/jscode
    
    COPY source/backend .
    
    ENTRYPOINT [ "npm", "run", "start" ]

     

    이미지 생성

    docker build -t app_test:prod -f app_test.dockerfile .

     

    nginx 프록시 설정을 위한 default.conf 내용 정의

    upstream app { //app으로 이름 정의
        server app_test:3001;  //app_test는 컨테이너 이름이지만 실제는 IP(192.xxx.xxx.xxx)
    }
    
    server {
        listen 80;
    
        location /v1 { //v1 경로일경우 다음 url으로 매핑시킨다
            proxy_pass http://app; //app은 upstream에서 정의한 이름
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    
        location / {
            root   /home/jscode;
            index  index.html;
            try_files $uri /index.html;
        }
    }

    경로는 ./docker/source/nginx 에 만들어둡니다. (이후 볼륨매핑을 위해)

     

    docker-compose.yml 내용 정의

    version: "3.5"
    
    services:
      app:
        container_name: app_test
        image: app_test:prod
        ports:
          - 3001:3001
    
      nginx:
        container_name: nginx_test
        image: nginx:1.23-alpine
        volumes:
          - ./docker/source/frontend/build:/home/jscode
          - ./docker/source/nginx:/etc/nginx/conf.d
        command: sh -c "nginx && tail -f /dev/null"
        ports:
          - 80:80

     

    nginx 컨테이너를 띄울때는 build 된 정적파일과 정의한 nginx deafult.conf를 매핑시키고 실행시킵니다.

     

    docker-compose 명령어로 컨테이너 실행

    docker-compose up -d

     

    localhost:80으로 접속해도 잘 나오고, localhost/v1으로 접속해도 잘 나옴을 확인할 수 있습니다.

    댓글

Designed by Tistory.