Skip to content

Instantly share code, notes, and snippets.

@robert-kratz
Created May 18, 2024 14:17
Show Gist options
  • Save robert-kratz/bdc108dcce90b20c5c6a35f9c516c3ba to your computer and use it in GitHub Desktop.
Save robert-kratz/bdc108dcce90b20c5c6a35f9c516c3ba to your computer and use it in GitHub Desktop.
This script will build a docker file for a webserver, then it will secure it via ssl and deploy the webserver.
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 4 ]; then
echo "Usage: $0 <domain> <port> <dockerfile_dir> <email>"
exit 1
fi
DOMAIN=$1
PORT=$2
DOCKERFILE_DIR=$3
EMAIL=$4
CONTAINER_NAME="${DOMAIN//./_}"
# Create the initial Nginx configuration for the domain in sites-available
NGINX_AVAILABLE_CONFIG="/etc/nginx/sites-available/$DOMAIN"
cat > $NGINX_AVAILABLE_CONFIG <<EOF
server {
listen 80;
listen [::]:80;
server_name $DOMAIN;
root /var/www/example.com;
index index.html;
location / {
try_files \$uri \$uri/ =404;
}
}
EOF
# Ensure symbolic link is created in sites-enabled directory
ln -sfn $NGINX_AVAILABLE_CONFIG /etc/nginx/sites-enabled/$DOMAIN
# Build and run the Docker container
cd $DOCKERFILE_DIR
docker build -t $CONTAINER_NAME .
docker stop $CONTAINER_NAME || true
docker rm $CONTAINER_NAME || true
docker run -d --name $CONTAINER_NAME -p $PORT:3000 $CONTAINER_NAME
# Restart Nginx to apply the initial configuration
sudo systemctl restart nginx
# Obtain SSL certificate using Certbot
sudo certbot --nginx -d $DOMAIN --non-interactive --agree-tos --email $EMAIL
# Create the final Nginx configuration for the domain in sites-enabled
NGINX_ENABLED_CONFIG="/etc/nginx/sites-enabled/$DOMAIN"
cat > $NGINX_ENABLED_CONFIG <<EOF
server {
server_name $DOMAIN;
client_max_body_size 100M;
root /var/www/example.com;
index index.html;
location / {
proxy_pass http://127.0.0.1:$PORT;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if (\$host = $DOMAIN) {
return 301 https://\$host\$request_uri;
} # managed by Certbot
server_name $DOMAIN;
listen 80;
return 404; # managed by Certbot
}
EOF
# Restart Nginx again to apply the final SSL configuration
sudo systemctl restart nginx
echo "Deployment complete. $DOMAIN is now accessible over HTTPS."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment