[Next.js] linux 서버에서 nginx로 nextjs 배포하기

양찌·2022년 10월 31일
5

Next.js

목록 보기
1/2

1. nginx 역할

  • nextjs는 javascript serverless framework임
    - 서버가 없으므로 nextjs를 실행해주는 서버가 필요
    - nginx는 웹서버 구축을 도와주는 소프트웨어
  • 사용자가 검색창에 url을 입력하면 nginx가 중간에서 linux 환경(OCI)에서 실행되고 있는 nextjs프로젝트를 보여줌
    - 클라이언트로부터 요청을 받았을 때 요청에 맞는 정적 파일을 응답해주는 HTTP Web Server로 활용
  • Reverse Proxy Server로 활용 → WAS 서버의 부하를 줄일 수 있는 로드 밸런서로 활용





2. ssl 인증서 파일 생성

나는 회사에서 구매한 ssl 인증서인 .pfx 파일을 이용하여 ssl 설정을 하였다.

.pfx 파일로 .crt, .rsa 파일 생성하기

인증서 .crt, .rsa 키 생성

openssl pkcs12 -in /usr/local/nginx/ssl/xxx.pfx -clcerts -nokeys -out /usr/local/nginx/ssl/xxx.crt
openssl pkcs12 -in /usr/local/nginx/ssl/xxx.pfx -nocerts -nodes -out /usr/local/nginx/ssl/xxx.rsa

인증서 정확성 검증

  • 443 포트로 정확성 검증을 함으로 443 포트가 사용 중이라면 프로세스를 종료하고 정확성 검증을 한다.
openssl s_server -www -accept 443 -cert /usr/local/nginx/ssl/xxx.crt -key /usr/local/nginx/ssl/xxx.rsa




3. /etc/nginx/nginx.conf 파일 설정

  • nginx.conf, conf.d/defaut.cof, site-available/default.conf 등등 많은데, 코드만 이해하면 된다.
  • nginx.conf는 최상위 nginx 실행파일이라 생각하면 됨
  • nginx.conf에 "include" 를 통해 하위 파일( conf.d/.cof, site-available/.conf)이 실행됨
// /etc/nginx/nginx.conf

user  root;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice; // nginx 에러가 나는 경우 error.log에서 확인


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    autoindex       on;
    keepalive_timeout  65;

    include /etc/nginx/conf.d/*.conf; 
    // /etc/nginx/conf.d/ 안에 있는 .conf로 된 모든 파일들을 이 파일에서 실행시킴

}




4. /etc/nginx/conf.d/domain.conf 설정

  • /etc/nginx/nginx.conf 에서 include 명령어 라인에서 *.conf 파일(확장자가 conf 인 모든 파일)을 실행하도록 되어있으므로 파일명은 자유
  • 여러 프로젝트를 실행 시킬 것을 대비하면 파일명은 도메인 네임으로 하면 좋음
  • 아래 파일에서 root는 프로젝트 디렉토리이고, location은 실행중인 경로
    - '/'에 유의하자
    - alias 와 root 설정이 있는데, 어떻게 쓰이는지는 아래 링크를 참고
    https://stackoverflow.com/questions/10631933/nginx-static-file-serving-confusion-with-root-alias?rq=14

// /etc/nginx/conf.d/domain.conf

server {
    listen 80;
    listen [::]:80;
    server_name www.domain.com domain.com; // 도메인 명
	
   // 301은 리다이렉트를 의미
   // 사용자가 http(80번 포트)로 들어오면 https(443)로 리다이렉트 해줌 
   return 301 https://$host$request_uri; 
}



server {
   listen [::]:443 ssl;
   listen 443;

   server_name www.domain.com domain.com;
   root /www/domain_2022/; // 프로젝트 디렉토리

   location / {
        proxy_pass http://localhost:4000; // 4000번에서 실행 중인 nextjs 프로젝트로 연결
   }

   ssl on;
   ssl_certificate /etc/ssl/domain.crt;  // 위에서 
   ssl_certificate_key /etc/ssl/domain.rsa;
   ssl_prefer_server_ciphers on;

 }




5.nextjs 프로젝트를 4000번 포트로 실행

  • 프로젝트 디렉토리로 이동 → ( 프로젝트 빌드 ) → 프로젝트 백그라운드 실행

  • nextjs 프로젝트/package.json

// package.json

{
  "name": "homepage-2022",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p ${PORT:-4000}", // 4000번 포트에서 실행
    "lint": "next lint"
  },
  "dependencies": {
    // 생략
  },
  "devDependencies": {
   // 생략
  }
}




6. nginx 실행

  • nginx 실행은 어느 디렉토리에서 해도 무관
    - systemctl start nginx




7.nginx 관련 명령어

  • 실행 : systemctl start nginx
  • 재실행 : systemctl restart nginx
  • 중지 : systemctl stop nginx
  • 에러 로그 확인
    - systemctl status nginx
    - cat /var/log/nginx/error.log (nignx.conf 파일에서 설정한 error.log 파일)
  • 새로 생성한 nginx 설정 파일 정합성 확인 : nginx -t
profile
신입 개발자 입니다! 혹시 제 글에서 수정이 필요하거나, 개선될 부분이 있으면 자유롭게 댓글 달아주세요😊

2개의 댓글

comment-user-thumbnail
2023년 2월 22일

서버에 파일 올릴 땐 전체 파일 다 올리는건가요? 기본 리액트는 빌드 된 것만 올리는데 넥스트는 어떤식으로 올리는건지요.?

1개의 답글