Tutorial: Creating a WebSocket Chat Application, Dockerizing, and Deploying on EC2 with NGINX and SSL

Nick Jabs
2 min readDec 11, 2023

--

Photo by Jaycee Xie on Unsplash

Step 4: Pulling the Docker Image, Setting Up NGINX, and Enabling SSL

  1. SSH into your EC2 instance:
ssh -i your-ec2-key.pem ec2-user@ec2-xx-xx-xx-xx.compute-1.amazonaws.com
  1. Replace your-ec2-key.pem with your EC2 key pair file and ec2-xx-xx-xx-xx.compute-1.amazonaws.com with your EC2 instance's public DNS.
  2. Pull the Docker image from Docker Hub:
  3. On the EC2 instance, pull the Docker image you pushed to Docker Hub:
docker pull your-docker-username/my-websocket-app:latest
  1. Replace your-docker-username with your actual Docker Hub username.
  2. Run the Docker container on EC2:
  3. Once the image is pulled, run the container on the EC2 instance:
docker run -d -p 8080:8080 --name my-websocket-app your-docker-username/my-websocket-app:latest
  1. This command starts the container in detached mode, mapping port 8080 of the EC2 instance to port 8080 of the container.

Setting Up NGINX and Enabling SSL:

  1. Install NGINX:
  2. Install NGINX on your EC2 instance:
Configure NGINX:sudo yum update -y
sudo amazon-linux-extras install nginx1 -y
sudo systemctl start nginx
  1. Edit the NGINX configuration file to set up a reverse proxy for the WebSocket server:
sudo nano /etc/nginx/nginx.conf
  1. Add the following configuration at the end of the http block:
server {
listen 80;
server_name your-domain.com;

location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
  1. Replace your-domain.com with your actual domain name.
  2. Enable SSL with Let’s Encrypt (Certbot):
  3. Install Certbot to obtain an SSL certificate for your domain:
sudo yum install certbot python3-certbot-nginx -y
  1. Obtain the SSL certificate:
sudo certbot --nginx -d your-domain.com
  1. Follow the prompts to configure Certbot. Once done, Certbot will automatically set up SSL for NGINX and renew the certificates.
  2. Restart NGINX:
  3. Restart NGINX to apply the changes:
sudo systemctl restart nginx
  1. Ensure that NGINX is running and SSL is enabled by visiting https://your-domain.com.

This concludes Step 4. Now your WebSocket application should be running behind NGINX with SSL enabled on your EC2 instance.

--

--