Skip to content

Instantly share code, notes, and snippets.

@JamesTheHacker
Last active December 2, 2018 22:24
Show Gist options
  • Save JamesTheHacker/9b85f1ccf05cb713356068529925a312 to your computer and use it in GitHub Desktop.
Save JamesTheHacker/9b85f1ccf05cb713356068529925a312 to your computer and use it in GitHub Desktop.
A bash script to provision a small node server
#!/bin/bash
UNPRIVILAGED_USER=roger_the_dodger
CERTBOT_EMAIL=your@email.here
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