Tutorial: Creating a WebSocket Chat Application, Dockerizing, and Deploying on EC2 with NGINX and SSL
Step 4: Pulling the Docker Image, Setting Up NGINX, and Enabling SSL
- SSH into your EC2 instance:
ssh -i your-ec2-key.pem ec2-user@ec2-xx-xx-xx-xx.compute-1.amazonaws.com
- Replace
your-ec2-key.pem
with your EC2 key pair file andec2-xx-xx-xx-xx.compute-1.amazonaws.com
with your EC2 instance's public DNS. - Pull the Docker image from Docker Hub:
- On the EC2 instance, pull the Docker image you pushed to Docker Hub:
docker pull your-docker-username/my-websocket-app:latest
- Replace
your-docker-username
with your actual Docker Hub username. - Run the Docker container on EC2:
- 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
- This command starts the container in detached mode, mapping port
8080
of the EC2 instance to port8080
of the container.
Setting Up NGINX and Enabling SSL:
- Install NGINX:
- Install NGINX on your EC2 instance:
Configure NGINX:sudo yum update -y
sudo amazon-linux-extras install nginx1 -y
sudo systemctl start nginx
- Edit the NGINX configuration file to set up a reverse proxy for the WebSocket server:
sudo nano /etc/nginx/nginx.conf
- 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";
}
}
- Replace
your-domain.com
with your actual domain name. - Enable SSL with Let’s Encrypt (Certbot):
- Install Certbot to obtain an SSL certificate for your domain:
sudo yum install certbot python3-certbot-nginx -y
- Obtain the SSL certificate:
sudo certbot --nginx -d your-domain.com
- Follow the prompts to configure Certbot. Once done, Certbot will automatically set up SSL for NGINX and renew the certificates.
- Restart NGINX:
- Restart NGINX to apply the changes:
sudo systemctl restart nginx
- 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.