Please wait...

小波Note

四川 · 成都市14 ℃
English

Various ways to deploy projects to servers

成都 (cheng du)9/20/2024, 12:18:04 AM2.67kEstimated reading time 8 minFavoriteCtrl + D / ⌘ + D
cover
IT FB(up 主)
Back-end development engineer
Article summary
Github Copilot

Loading article summary...

Deploying projects using various methods: build, transfer, and deploy.

Without CI/CD

Generate key pairs

bash
        # Default -> ~/.ssh/id_rsa
ssh-keygen -t rsa -b 4096 -C "xxx"
# Specify file name -> ~/.ssh/id_rsa_deploy
ssh-keygen -t rsa -b 4096 -C "xxx" -f ~/.ssh/id_rsa_deploy

    

The site owner has specifically generated a key pair for deployment, so it won't affect other key pairs.

You need to place the contents of id_rsa_deploy.pub into the server's ~/.ssh/authorized_keys file, so you can log in without a password.

By default, the id_rsa key is used. If you want to use another key, there are two methods:

  1. You can specify the key file in the deploy.sh script
deploy.sh
        #!/bin/bash
ssh -i ~/.ssh/id_rsa_xxx root@xxx.xxx.xxx.xxx [command to execute]

    
  1. Configure the ~/.ssh/config file. This way, you can directly use the ssh deploy command in the deploy.sh script.
~/.ssh/config
        # Use a specific key for a specific server
Host deploy
  HostName xxx.xxx.xxx.xxx
  User root
  IdentityFile ~/.ssh/id_rsa_deploy

    
deploy.sh
        #!/bin/bash
ssh deploy [command to execute]

    

During execution, you will encounter the issue of entering the password. This script will prompt for the SSH key password three times: Enter passphrase for key '/c/Users/Linux/.ssh/id_rsa_deploy':. You can use the ssh-add command to add the key to the ssh-agent so that you won't be prompted for the password again.

bash
        # SSH agent
eval "$(ssh-agent -s)"
# Add key
ssh-add ~/.ssh/id_rsa_deploy
# List added keys
ssh-add -l
# Kill SSH agent
ssh-agent -k

    

Complete run script, only prompts for password once

deploy.sh
        #!/bin/bash

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa_deploy

echo "Building project"
pnpm run build

echo "Compressing files..."
tar -zcvf .output.tar.gz .output

echo "Stopping service"
ssh deploy "cd /usr/local/app/node_run/it-fb && pm2 stop ecosystem.config.cjs && rm -rf .output.bak && mv .output .output.bak"

echo "Uploading files..."
scp .output.tar.gz deploy:/usr/local/app/node_run/it-fb

echo "Starting service"
ssh deploy "cd /usr/local/app/node_run/it-fb && tar -zxvf .output.tar.gz && pm2 start ecosystem.config.cjs && rm -rf .output.tar.gz"

echo "Deployment complete"
rm -rf .output.tar.gz

ssh-agent -k

    

Run

package.json
        {
  "scripts": {
    "deploy": "sh ./deploy.sh"
  }
}

    
bash
        # On Windows, run in Git Bash
pnpm run deploy