Skip to content

Instantly share code, notes, and snippets.

@JeremyJaydan
Last active February 20, 2024 14:53
Show Gist options
  • Save JeremyJaydan/ad7c2d11ff9488df140e2ab62ef523a3 to your computer and use it in GitHub Desktop.
Save JeremyJaydan/ad7c2d11ff9488df140e2ab62ef523a3 to your computer and use it in GitHub Desktop.

Deployment Pipeline

Setting up your codebase

  1. GitHub actions config
name: Deploy
on:
  push:
    branch: release

jobs:

  production:
    runs-on: target
    steps:

      - name: Docker Prune
        run: sudo docker system prune -f

      - name: Checkout repository
        uses: actions/checkout@v4
        
      - name: Build docker image
        run: sudo docker build . --build-arg DOT_ENV=$(cat ~/.env | base64 -w 0) --file Dockerfile --tag example:latest

      - name: Run docker container
        run: |
          sudo docker run -d --name=server-${{ github.sha }} -p 80 example:latest
          echo "port=$(sudo docker port $(sudo docker ps -ql) | awk -F: '{print $2}' | tr -d '\r\n[:space:]')" >> $GITHUB_ENV
                    
      - name: Reroute traffic
        run: |
          sudo sed -i "s/\(\b[0-9]\{4,8\}\b\)/$port/" /etc/nginx/sites-available/jeremyjaydan.conf
          sudo systemctl reload nginx
          
      - name: Stop old production container(s)
        run: |
          sudo docker stop $(sudo docker ps -q --filter name=server | grep -v $(sudo docker ps -q --filter name=server-${{ github.sha }}))
  1. Dockerfile
FROM node:20-alpine

ENV APP_HOME /home/jeremy

WORKDIR $APP_HOME
COPY . .

# use host .env
ARG DOT_ENV
RUN echo $DOT_ENV | base64 -d >> .env

# random string for cache invalidation purposes in the application layer 
RUN echo "BASE64_DATE_STRING=$(date | base64)" >> .env

RUN npm i && npm run build
CMD npm run start

Setting up the server

  1. Creating the server user
$ sudo adduser --disabled-password server
$ sudo usermod -aG sudo server
  1. Install docker (debian): https://docs.docker.com/engine/install/debian/#install-using-the-repository

  2. Install nginx https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-open-source/#installing-prebuilt-debian-packages

$ sudo nano /etc/nginx/sites-available/example.conf
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:32769;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
$ sudo ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
$ sudo systemctl reload nginx
  1. Install GitHub Actions: Follow the instructions in GitHub settings: https://github.com/PurpleOre/discadia/settings/actions/runners/new?arch=x64&os=linux

  2. Install Cloudflared:

Sudo password issues? Try changing/adding this via 'visudo':
%sudo   ALL=(ALL:ALL) NOPASSWD: ALL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment