Deploying projects using various methods: build, transfer, and deploy.
Without CI/CD
Generate key pairs
# 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:
- You can specify the key file in the
deploy.sh
script
#!/bin/bash
ssh -i ~/.ssh/id_rsa_xxx root@xxx.xxx.xxx.xxx [command to execute]
- Configure the
~/.ssh/config
file. This way, you can directly use thessh deploy
command in thedeploy.sh
script.
# Use a specific key for a specific server
Host deploy
HostName xxx.xxx.xxx.xxx
User root
IdentityFile ~/.ssh/id_rsa_deploy
#!/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.
# 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
#!/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
{
"scripts": {
"deploy": "sh ./deploy.sh"
}
}
# On Windows, run in Git Bash
pnpm run deploy