Open a custom port on AWS Cloud9

      1 min read  

Suppose you have created a custom application with your Cloud9 IDE. The application creates a local web server on port 3000 (typical for NodeJS apps). Lets assume the following code:

// save in server.js
const http = require('http')
const port = 3000

const requestHandler = (request, response) => {
  console.log(request.url)
  response.end('Hello Node.js Server!')
}

const server = http.createServer(requestHandler)

server.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

Start the server using:

$ node server.js

By default, this will not work because your the ec2 instance this code is run on has not configured to allow incoming TCP connections on port 3000 yet. You can either change this in the security group’s inbound rule-set or by using the following script:

PORT=3000
ENV=dev

GROUP=`aws ec2 describe-instances --filters "Name=tag:Name,Values=*$ENV*" --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' --output text`
aws ec2 authorize-security-group-ingress --protocol tcp --port $PORT --cidr 0.0.0.0/0 --group-id $GROUP

Change the PORT variable to the port number you desire. Change the ENV variable to the name of your cloud9 environment. See the official documentation for more help.

Additionally I’ve written a simple script that does just that:

sh aws-c9-openport dev 3000 `

The script can be found in the GitHub repo here.