Last active
December 2, 2018 22:24
-
-
Save JamesTheHacker/9b85f1ccf05cb713356068529925a312 to your computer and use it in GitHub Desktop.
A bash script to provision a small node server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
UNPRIVILAGED_USER=roger_the_dodger | |
[email protected] | |
APP_DIR=$UNPRIVILAGED_USER_HOME/api | |
PM2=$APP_DIR/node_modules/pm2/bin/pm2 | |
UNPRIVILAGED_USER_HOME=/home/$UNPRIVILAGED_USER | |
NODE_VERSION=https://deb.nodesource.com/setup_10.x | |
# Update before downloading Node install script | |
sudo apt-get update | |
# Download Node install script. Trusted source! | |
curl -sL $NODE_VERSION | sudo -E bash - | |
# Install required packages | |
sudo apt-get update | |
sudo apt-get install -y \ | |
build-essential \ | |
nginx \ | |
software-properties-common \ | |
python \ | |
nodejs | |
# Generate SSL certificate and automatically configure nginx in production | |
if [[ $NODE_ENV == "production" ]]; | |
then | |
echo "Setting up LetsEncrypt SSL ..." | |
sudo add-apt-repository ppa:certbot/certbot | |
sudo apt-get update | |
sudo apt-get install python-certbot-nginx | |
sudo certbot \ | |
--standalone \ | |
--agree-tos \ | |
--non-interactive \ | |
--email $CERTBOT_EMAIL \ | |
--nginx | |
fi | |
# Create new unprivilated user | |
echo "Adding unprivilaged user ..." | |
sudo adduser --disabled-password --gecos "" $UNPRIVILAGED_USER | |
# Copy SSH config | |
echo "Securing SSH ..." | |
sudo mv /tmp/server/config/ssh_config /etc/ssh/ssh_config | |
sudo systemctl restart sshd | |
# Copy nginx default | |
echo "Copying nginx site config ..." | |
sudo mv /tmp/server/config/default /etc/nginx/sites-available/default | |
sudo systemctl restart nginx | |
# Move application files to home dir | |
echo "Copying application to unprivilaged user home directory ..." | |
sudo rsync -a /tmp/server/ $APP_DIR | |
sudo chown -R $UNPRIVILAGED_USER:$UNPRIVILAGED_USER $APP_DIR | |
sudo runuser -l $UNPRIVILAGED_USER -c "npm install --prefix $APP_DIR" | |
# Configure pm2 | |
echo "Configuring pm2 ..." | |
sudo runuser -l $UNPRIVILAGED_USER -c "$PM2 start $APP_DIR/server.js --watch" | |
sudo $PM2 startup systemd | |
sudo env PATH=$PATH:/usr/bin $PM2 startup systemd -u $UNPRIVILAGED_USER --hp $APP_DIR | |
# Setup firewall | |
echo "Configuring firewall ..." | |
sudo ufw default deny incoming | |
sudo ufw default allow outgoing | |
sudo ufw allow ssh | |
sudo ufw allow http | |
sudo ufw allow https | |
# Start UFW | |
echo "Restarting firewall ..." | |
sudo ufw --force enable | |
# Clean up | |
echo "Cleaning up ..." | |
sudo rm -rf /tmp/server | |
echo "Deployment Complete!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment