AWS Lightsail 서버를 활용하여 Quasar 프레임워크(Vue.js 기반)로 개발된 SPA(Single Page Application)를 배포하는 전체 과정을 정리해보려고 한다. Docker와 Nginx를 사용하고, Vue Router의 History 모드와 Hash 모드의 차이점 및 설정 방법을 다룰 것이다.
Ubuntu 서버를 선택하여 Lightsail 인스턴스 생성
SSH 키를 다운로드하거나 브라우저 기반 SSH 사용하여 서버 접속
sudo apt update
sudo apt upgrade -y
기본적으로 우분투에 ssh로 접속하는 방식은 ssh ubuntu@3.35.51.40을 입력하고, 설정한 비밀번호를 입력하면 된다. 다만 ssh key를 lightsail에 등록한 경우는 비밀번호 입력 없이 접속할 수 있고 비밀번호를 설정할 때도, 기존의 비밀번호가 필요하지 않다.
root로 로그인하기 위해서는 etc/ssh/sshd_config 파일의 내용을 변경해야 한다.
vi 편집기를 통해 #PermitRootLogin prohibit-password 부분에서 #을 삭제하고, prohibit-password를 yes로 변경해주면 된다.
다음으로 sudo systemctl restart ssh로 재설정을 해준다. /root/.ssh/authorized_key 파일의 제한된 명령어를 변경한다. vi 편집기를 통해서 command="echo 'Please login as the user \"ubuntu\" rather than the user \"root\".';echo;sleep 10;exit 142 이 부분을 삭제하고 ssh-ed~ 이 부분부터를 남겨주고 권한 설정을 한다.
마지막으로
chmod 600 authorized_keys
chown root:root authorized_keys
권한 설정을 마치고 나면 끝이다. 당연히 재시작을 해준다.
Docker를 사용하면 애플리케이션과 그 의존성을 컨테이너로 패키징하여 일관된 환경을 제공할 수 있다. 앞서 제공한 포스팅에서 도커 설치에 관한 부분은 정리해두었다.
앞선 포스팅은 도커를 설치하고 nginx를 만드는 과정이 담겨져 있다. 이 부분을 다른 방식으로도 실행할 수 있다.
# Docker 설치에 필요한 패키지 설치
sudo apt install apt-transport-https ca-certificates curl software-properties-common
# Docker 공식 GPG 키 추가
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
# Docker 저장소 추가
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
# 패키지 목록 업데이트
sudo apt update
# Docker CE 설치
sudo apt install docker-ce
# Docker Compose 설치
sudo apt install docker-compose
# Nginx 설정을 위한 디렉토리 생성
mkdir -p /opt/nginx/conf
mkdir -p /opt/nginx/html
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html:ro
- ./conf/default.conf:/etc/nginx/conf.d/default.conf:ro
networks:
- webnet
networks:
webnet:
driver: bridge
server {
listen 80;
server_name pqmservice;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
##try_files $uri index.html; - SPA의 history 모드를 사용할 때는 이렇게 하고, 전자는 hash 모들르 사용할 때
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
expires off;
}
}
Nginx에 생성하는 default.conf 파일의 내용은 다음과 같다.
listen 80: 80 포트를 리스닝
server_name: 서버 이름 설정
root: 웹 루트 디렉토리 지정
index: 기본 인덱스 파일 지정
location /: 모든 요청 처리 규칙
try_files $uri $uri/ /index.html: SPA의 History 모드를 위한 핵심 설정
요청된 경로에 파일이 있는지 확인하고, 없으면 index.html로 라우팅
캐시 관련 헤더 설정으로 항상 최신 콘텐츠 제공
try_files 부분아래 주석을 첨부한 것은 hash 모드를 이용할 때 사용하는 코드이다.
Hash 모드와 History 모드의 차이점
Vue Router에는 두 가지 주요 라우팅 모드가 있다. hash 모드는 Hash 모드: URL에 #이 포함되고(예: http://3.35.51.40/#/login), History 모드는 일반 웹사이트처럼 깔끔한 URL (예: http://3.35.51.40/login)이 제공된다. hash는 서버 설정이 간단하며 모든 웹 서버에서 작동한다. 다만 미관상 #이 포함되어 좋지 않으며 SEO에 불리하다는 단점이 있다. 반면 history모드는 url이 깔끔하며 SEO에 유리하다는 장점이 있지만 특별한 서버 설정이 필요하여 모든 경로를 index.html로 리다이렉션해줘야 한다. 설정이 없다면 404오류가 발생하게 된다.
Hash 모드는 서버 구성을 변경할 수 없는 정적 호스팅에 적합하고 History 모드는 사용자 경험과 SEO가 중요한 대규모 애플리케이션에 적합하다. 두 모드 모두 초기 로딩 후에는 클라이언트에서 라우팅을 처리하지만, 사용자가 URL을 직접 입력하거나 새로고침할 때의 처리 방식에 차이가 있는 것이다.
cd /opt/nginx
docker-compose up -d
package.json에 배포 스크립트를 추가한다.
"scripts": {
"test": "echo \"No test specified\" && exit 0",
"dev": "quasar dev",
"build": "quasar build",
"deploy": "scp -r dist/spa/* root@3.35.51.40:/opt/nginx/html"
}
scp -r은 Secure Copy Protocol의 약자로 ssh를 통해 파일을 원격 서버로 안전하게 전송하는 역할을 하는 명려어이다. -r 옵션은 디렉토리와 그 내용을 재귀적으로 복사한다는 의미이다.
먼저 빌드를 통하여 dist/spa 디렉토리에 배포할 내용을 생성한다.
다음으로 deploy를 통하여 해당 디렉토리의 모든 내용을 nginx/html 디렉토리로 배포한다.
코드에서 quasar.config.js에 설정을 변경한다.
// quasar.config.js
build: {
env: require('dotenv').config().parsed,
target: {
browser: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
node: 'node16'
},
vueRouterMode: 'history', // 또는 'hash'
// ...
}
서버측에는 default.conf 파일을 변경해주면 된다.
server {
listen 80;
server_name pqmservice;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri /index.html;
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
expires off;
}
}
변경 이후에는 nginx 디렉토리로 이동하여 컨테이너를 재시작해준다.
cd /opt/nginx
docker-compose down
docker-compose up -d
만약 error가 발생한다면 docker-compose가 설치되어 있지 않을 수도 있으니, 설치 후 컨테이너를 재시작하고 down, up -d를 해주면 되겠다.
apt install docker-compose
# 현재 실행 중인 컨테이너 확인
docker ps
# 설정 파일 수정 후 컨테이너 재시작
docker restart 앞서확인한컨테이너_ID
해당 설정을 모두 마친다면 이후에는 문제없이 웹서버를 사용할 수 있을 것이다.