[WIP] Next.js 프로젝트를 EC2에서 PM2로 배포하기(+Nginx, docker-compose)

2024. 11. 23. 18:15

1. 간단하게 먼저 pm2로 배포하기

1.1 생성한 ec2에 key.pem으로 원격 접속

ssh -i "pwa-test-key.pem" ubuntu@123.**.**.**

 

1.2 sudo su로 관리자 권한으로 변경하고, node.js 설치
(참고로 nvm을 사용한 방식과 아래와 같이 apt 패키지 관리자를 사용하는 방식이 있는데, 하나의 Node.js 버전을 사용할 예정이라서 아래 방식을 사용하였다. nvm을 사용하면 상황에 따라 여러 버전의 Node.js를 사용하기 편리하다.)

apt-get update &&
apt-get install -y ca-certificates curl gnupg &&
mkdir -p /etc/apt/keyrings &&
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg &&
NODE_MAJOR=20 &&
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list &&
apt-get update &&
apt-get install nodejs -y

(설명)
apt 패키지 관리자 업데이트부터 하고 ca-certificates, curl, gnupg를 설치함

  • ca-certificates: SSL 인증서 관리 도구 (보안 연결을 위한 필수 패키지)
  • curl: HTTP 요청을 보내는 CLI 도구 (외부 리소스를 다운로드)
  • gnupg: GPG 키 관리 도구 (패키지 서명을 검증)

그 다음, GPG 키 저장 디렉터리 생성하고, Node.js 저장소의 GPG 키를 다운로드하여 /etc/apt/keyrings/nodesource.gpg 파일로 저장

  • curl -fsSL: 다운로드 중 에러 메시지를 숨기고 파일 내용을 표준 출력으로 전달.
  • gpg --dearmor: ASCII 포맷의 GPG 키를 바이너리로 변환.

그런 다음, Node.js의 APT 저장소를 추가하는데, 20버전을 변수로 선언하여 사용한다.

  • /etc/apt/sources.list.d/nodesource.list: Node.js 저장소가 추가될 파일 위치.

최종적으로 추가된 Node.js 저장소를 반영하여 패키지 정보를 업데이트하기 위해 apt-get update
패키지관리자를 통해 nodejs를 설치하면 끝.

 

node -v로 설치 잘 됐는지 확인.

 

 

1.3 pnpm 설치하고,

npm install -g pnpm

 

1.4 배포할 코드 준비.
내 프로젝트 clone 하고 프로젝트 디렉토리로 가서 vi .env 파일 추가해주고,

pnpm install && pnpm build

 

1.5 pm2 설치하고,

npm install -g pm2

 

1.6 pm2 프로세스 생성(운영 환경)

pm2 --name "nextjs-app" start pnpm -- start

 

1.7 인바운드 규칙 추가

그런데, pnpm start 명령을 사용하기 위해 포트 설정이 필요함.

포트 3000을 쓰고 있기 때문에 ec2에 적용한 보안그룹 내 인바운드 규칙에 3000 포트가 존재해야 한다. 3000포트에 열려있어야 함.

이제 내 ec2 퍼블릭 ip에서 3000으로 접속하면 배포가 잘 된 것을 확인할 수 있다.

http://123.***.**.**:3000

 

 

2. nginx 도입

이제는 뒤에 포트를 붙이지 않고 도메인을 연결하고 싶어서 엔진엑스를 도입하려고 한다.

2.0 테스트용으로 무료도메인을 구해서 ec2 퍼블릭 ip를 연결시켰다.

https://xn--220b31d95hq8o.xn--3e0b707e/

 

내도메인.한국 - 한글 무료 도메인 등록센터

한글 무료 도메인 내도메인.한국, 웹포워딩, DNS 등 무료 도메인 기능 제공

xn--220b31d95hq8o.xn--3e0b707e

 

 

2.1 nginx 설치 및 기본 파일 정리

패키지매니저 업데이트 && nginx 설치

sudo apt update && sudo apt install nginx -y
nginx -v

/etc/nginx 로 이동하여 구조 확인 tree .

nginx.conf는 전역 설정 파일이고, sites-available과 sitres-enabed에서 실질적으로 설정을 할 것이다.

sites-available는 설정 파일을 저장하는 디렉토리이며, 이 설정을 적용하려면 해당 파일을 sites-enabled 디렉토리에 심볼릭 링크로 연결해야 한다.

즉, sites-enabled/default → /etc/nginx/sites-available/default 이 화살표의 의미는
sites-enabled는 활성화된 설정을 포함하며, 파일의 원본은 sites-available에 위치한다는 의미이다.

 

sitres-available/default 파일 내용은 이러하다.

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
	listen 80 default_server;
	listen [::]:80 default_server;

	# SSL configuration
	#
	# listen 443 ssl default_server;
	# listen [::]:443 ssl default_server;
	#
	# Note: You should disable gzip for SSL traffic.
	# See: https://bugs.debian.org/773332
	#
	# Read up on ssl_ciphers to ensure a secure configuration.
	# See: https://bugs.debian.org/765782
	#
	# Self signed certs generated by the ssl-cert package
	# Don't use them in a production server!
	#
	# include snippets/snakeoil.conf;

	root /var/www/html;

	# Add index.php to the list if you are using PHP
	index index.html index.htm index.nginx-debian.html;

	server_name _;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	# pass PHP scripts to FastCGI server
	#
	#location ~ \.php$ {
	#	include snippets/fastcgi-php.conf;
	#
	#	# With php-fpm (or other unix sockets):
	#	fastcgi_pass unix:/run/php/php7.4-fpm.sock;
	#	# With php-cgi (or other tcp sockets):
	#	fastcgi_pass 127.0.0.1:9000;
	#}

	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	#location ~ /\.ht {
	#	deny all;
	#}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#	listen 80;
#	listen [::]:80;
#
#	server_name example.com;
#
#	root /var/www/example.com;
#	index index.html;
#
#	location / {
#		try_files $uri $uri/ =404;
#	}
#}

 

2.2 이러한 기본 파일을 참조해서 내 설정파일을 생성한다.