How to run two applications on one port?
sobes.tech AI
Answer from AI
It is not possible to directly run two different applications on the same TCP port because a port can be occupied by only one process. However, there are several approaches to bypass this limitation:
-
Use a reverse proxy — run a proxy server (for example, Nginx or an embedded Go HTTP reverse proxy) that listens on the required port and routes requests to different applications running on different internal ports.
-
Multiplex protocols — if applications use different protocols or can distinguish requests, you can write a demultiplexer application that accepts all connections on one port and redirects them based on the content.
-
Use Unix domain sockets or other IPC — if applications need to interact, you can run one application on a port and another on a socket, and configure the interaction.
Example with reverse proxy in Go:
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
)
func main() {
target1, _ := url.Parse("http://localhost:8081")
target2, _ := url.Parse("http://localhost:8082")
proxy1 := httputil.NewSingleHostReverseProxy(target1)
proxy2 := httputil.NewSingleHostReverseProxy(target2)
http.HandleFunc("/app1/", func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = r.URL.Path[len("/app1"):]
proxy1.ServeHTTP(w, r)
})
http.HandleFunc("/app2/", func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = r.URL.Path[len("/app2"):]
proxy2.ServeHTTP(w, r)
})
log.Println("Starting proxy on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Here, the proxy listens on port 8080 and redirects requests with prefixes /app1/ and /app2/ to different applications running on 8081 and 8082.