Instantly share code, notes, and snippets.

Embed
What would you like to do?
Socket.io EC2 bootstrap
sudo yum -y install nginx
sudo mkdir /etc/nginx/ssl
sudo openssl req -nodes -x509 -days 1024 -newkey rsa:2048 -keyout /etc/nginx/ssl/server.key -out /etc/nginx/ssl/server.crt -subj '/C=US/ST=YOURSTATE/L=YOURCITY/O=YOURORG/OU=Web/CN=YOURWEBSITE'
sudo yum -y update
sudo yum install -y gcc-c++ make
sudo curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash -
sudo yum install -y nodejs
sudo npm install forever -g --save
sudo echo "map \$http_upgrade \$connection_upgrade {
default upgrade;
'' close;
}
# Create a socket upstream server for the proxy
upstream websocket {
server 127.0.0.1:5000;
keepalive 8;
}
add_header Strict-Transport-Security 'max-age=15768000' always;
server {
# Listen for HTTP to force SSL
listen 80;
# Listen for any traffic from ELB on 3000
listen 3000 ssl default_server ssl;
# Change this to whatever domain you've attached your ELB SSL to
server_name www.yourserver.com;
ssl on;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
ssl_session_timeout 5m;
# Force SSL
if ($ssl_protocol = '') {
rewrite ^ https://\$host\$request_uri? permanent;
}
# This is where the magic happens
location ~ ^/(chat|socket\.io)(.*)$ {
# Point our proxy to the socket upstream server
proxy_pass http://websocket;
# Forward headers from ELB
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection \$connection_upgrade;
proxy_redirect off;
proxy_buffers 8 32k;
proxy_buffer_size 64k;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header Host \$host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header X-Forwarded-Proto \$scheme;
}
# Pass on any 443 traffic (namely for ELB health checks) to a static site
root /var/www/html;
index index.html index.htm;
location ~ ^/(chat|socket\.io) {
try_files \$uri \$uri/ /index.html;
}
}" > /etc/nginx/conf.d/virtual.conf
sudo echo "var io = require('socket.io').listen(5000);
io.on('connection', function (socket) {
socket.on('join', function(e) {
console.log(socket.id);
});
socket.on('disconnect', function(e) {
console.log(socket.id);
});
});" > /home/ec2-user/socket.js
sudo service nginx start
sudo forever start /home/ec2-user/socket.js -O OUTPUT.log -e ERROR.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment