'How to start webserver in public port using Akka http in Scala

I am using the below code to start server to handle http request. It is working in local machine. As It is deployed in EC2 instance, though inbound rules are added, it is not available to public. It is accessible only inside EC2 instance using curl command.

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.Http
import akka.Done
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.StatusCodes
// for JSON serialization/deserialization following dependency is required:
// "com.typesafe.akka" %% "akka-http-spray-json" % "10.1.7"
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

import scala.io.StdIn

import scala.concurrent.Future


object WebServer {

  // needed to run the route
  implicit val system = ActorSystem(Behaviors.empty, "SprayExample")
  // needed for the future map/flatmap in the end and future in fetchItem and saveOrder
  implicit val executionContext = system.executionContext

  
  def main(args: Array[String]): Unit = {

    val bindingFuture = Http().newServerAt("localhost", 8080).bind(routes)
    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }
}

As I tried this , I am getting the below error.

val bindingFuture = Http().newServerAt("3.8.161.134", 8080).bind(routes)

16:39:36.811 [SprayExample-akka.actor.default-dispatcher-3] ERROR a.i.TcpListener - Bind failed for TCP channel on endpoint [/3.8.161.134:9000]
java.net.BindException: [/3.8.161.134:9000] Cannot assign requested address
        at java.base/sun.nio.ch.Net.bind0(Native Method)
        at java.base/sun.nio.ch.Net.bind(Net.java:459)
        at java.base/sun.nio.ch.Net.bind(Net.java:448)

What I should do to make the server and port available to outside EC2 instance?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source