Skip to main content

Using Nginx as a proxy to multiple Unix sockets



Using Nginx as a proxy to multiple Unix sockets




TL;DR Listening port may be a contended resource on a busy shared machine, unix sockets are virtually unlimited. Nginx can expose them with a single port and prefixed URLs.

In some situations you may want to run many (instances of) applications on a single machine. Each instance may need to provide internal information (e.g. Prometheus /metrics, profiling/debug handlers) over restricted HTTP.

When number of instances grows it becomes a burden to provision listening ports without conflicts. In contrast, using Unix sockets allows for more transparency (readable filenames) and scalability (easy to come up with unique name).

Here is a small demo program written in Go that would serve trivial HTTP service with Unix socket.

package main

import (
    "context"
    "flag"
    "io/fs"
    "log"
    "net"
    "net/http"
    "os"
    "os/signal"
)

func main() {
    var socketPath string

    flag.StringVar(&socketPath, "socket", "./soc1", "Path to unix socket.")
    flag.Parse()

    if socketPath == "" {
        flag.Usage()
        return
    }

    listener, err := net.Listen("unix", socketPath)
    if err != nil {
        log.Println(err.Error())
        return
    }

    // By default, unix socket would only be available to same user.
    // If we want access it from Nginx, we need to loosen permissions.
    err = os.Chmod(socketPath, fs.ModePerm)
    if err != nil {
        log.Println(err)
        return
    }

    httpServer := http.Server{
        Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
            log.Println(request.URL.String())
            if _, err := writer.Write([]byte(request.URL.String())); err != nil {
                log.Println(err.Error())
            }
        }),
    }

    // Setting up graceful shutdown to clean up Unix socket.
    go func() {
        sigint := make(chan os.Signal, 1)
        signal.Notify(sigint, os.Interrupt)
        <-sigint
        if err := httpServer.Shutdown(context.Background()); err != nil {
            log.Printf("HTTP Server Shutdown Error: %v", err)
        }
    }()

    log.Printf("Service is listening on socket file %s", socketPath)
    err = httpServer.Serve(listener)
    if err != nil {
        log.Println(err.Error())
        return
    }
}

Now let's run a couple of instances in separate shells.

./soc -socket /home/ubuntu/soc1
./soc -socket /home/ubuntu/soc2

Here is a minimal Nginx config to serve those instances with URL prefixes. It would receive http://my-host/soc1/foo/bar, strip path prefix /soc1 and pass /foo/bar to soc1.


to soc1.

server {
    listen 80 default;

    location /soc1/ {
        proxy_pass http://soc1/;
    }
    location /soc2/ {
        proxy_pass http://soc2/;
    }
}

upstream soc1 {
    server unix:/home/ubuntu/soc1;
}

upstream soc2 {
    server unix:/home/ubuntu/soc2;
}

Every Unix socket is defined as upstream and has /location statement in server.

It is also possible to use Unix sockets directly in /location, like in

    location /soc1/ {
        proxy_pass http://unix:/home/ubuntu/soc1;
    }

however it has an unwanted limitation that you can not add trailing / to proxy_pass. And this means that URL will be passed as is, e.g. soc1 will receive /soc1/foo instead of /foo.

To avoid such limitation we can use named upstream and add trailing / to proxy_pass.

    location /soc1/ {
        proxy_pass http://soc1/; # Mind trailing "/".
    }

Comments

Popular posts from this blog

How to Unlock M-kopa Phones in Kenya and Remove Kopa Bloatware

How to Unlock M-kopa Phones in Kenya how to unlock m-kopa phones in kenya How to remove mkopa account in your phone   M-Kopa Phones are ideally best last option when you don't have huge cash to buy a brand new phone. Why? Because they are cheap and readily available in nearly all market places. With these phones, you need to have a down payment ranging from 2000/- to 3000/-. They come with many advantages but the worst part is that you must make payments on daily basis to keep your m kopa Phone unlocked and operational. You might have landed here because you are probably wondering how to unlock m kopa Phone and go away without finishing your payments?.The following some simple steps on how to unlock any M Kopa phone without paying: Unlock m kopa Phone by uninstalling m kopa bloatware. What is bloatware? In another words, pre-installed apps that are useless most of the time, or system apps with super permissions. There are also other downfall of bloatware. It consumes system resourc

HOW TO HACK MKOPA, DAYLIGHT PHONES AND ESCAPE PAYMENT 2021

Hello there, paying ksh 20 everyday by pay as you go phone is really frustrating. Am going to teach you how you can unlock the phone and use it without daily payment, no tracking.  ⚠ Warning: This is only for educational purposes and not for any illegal use. Copyright © not accepted  Follow this simple process  Extract the content of the Miracle Box to your desktop. Open the folder and run "Miracle_Loader_2.27A" Wait till the Miracle Box program is launched Click on the MTK tab Click on the Unlock / Fix tab Tick Reset Code Click the dropdown box and select your chipset type MT**** Click the Start Button Connect the phone to the PC (must be switched off still with battery inside) Press the power button once (this is to ensure that your device is detected immediately). DO NOT hold down the power button else the phone will boot up normally Wait for the message ">>Done. (Need to wait a few minutes the phone is switched)" Disconnect and power on the pho

SAFARICOM WEBINAR 10 GB DATA 9TH NOVEMBER EVENT 2022

SAFARICOM WEBINAR 10 GB DATA 9TH NOVEMBER EVENT Learn what makes us unique among other international and African universities. If you are a young professional, our programs can  help you  in a  variety of ways  since each  study plan is tailored to your specific needs  and includes personalized assistance, allowing you to  study on your own terms  and according to your own schedule. Best of all, you can earn an  accredited degree  from Germany or the UK entirely online.   We regularly offer free webinars about studying at IU. These events give you the opportunity to get to know our University of Applied Sciences and our wide range of educational offerings. The webinars are hosted by our study advisors, who offer expert knowledge about studying at IU, as well as an opportunity to ask any questions you might have at the end of each webinar. Join our study advisors for an online webinar to understand various aspects of our  online and on campus  learning. This is your chance t