Skip to content

Instantly share code, notes, and snippets.

@iam-hussain
Last active March 6, 2023 18:29
Show Gist options
  • Save iam-hussain/459e21f252dcacc54142cd3cf9b68497 to your computer and use it in GitHub Desktop.
Save iam-hussain/459e21f252dcacc54142cd3cf9b68497 to your computer and use it in GitHub Desktop.
Use GitLab CI to build, deploy, restart the NextJS PM2 server in the AWS instance
# !/bin/bash
# <*> Add DEPLOY_SERVER_USER variable with the value of instanse user(eg:ubuntu) in GitLab CI setting.
# <*> Add DEPLOY_SERVER_URL variable with the value of instanse url(eg:http://ec2-XXXXX.XXX.amazonaws.com/) in GitLab CI setting.
echo "Deploying to ${DEPLOY_SERVER_USER}@${DEPLOY_SERVER_URL}"
ssh ${DEPLOY_SERVER_USER}@${DEPLOY_SERVER_URL} 'bash' < ./deploy/server.sh
# <*> replace PROJECT_DIRECTORY with you directory
cd PROJECT_DIRECTORY
git checkout .
git pull
# Build and deploy
npm ci
npm run build
# replace PM2_SERVICE_NAME with you pm2 name
pm2 restart PM2_SERVICE_NAME
exit
#Path: PROJECT_DIRECTORY/.gitlab-ci.yml
stages:
- build
- deploy
building:
stage: build
image: node:16
variables:
NODE_ENV: "production"
script:
- npm install
- npm run build
cache:
key: ${CI_PROJECT_ID}
paths:
- node_modules/
- .next/cache/
deployment:
stage: deploy
only:
- main
- master
before_script:
- apt-get update -qq
- apt-get install -qq git
- apt-get install -y npm
# Setup SSH deploy keys
- "which ssh-agent || ( apt-get install -qq openssh-client )"
- eval $(ssh-agent -s)
# <*> Add SSH_PRIVATE_KEY variable with the value of your SSL private key of the AWS in GitLab CI setting.
- ssh-add <(echo "$SSH_PRIVATE_KEY")
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
environment:
name: production
script:
- bash ./deploy/deploy.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment