Run an NGINX proxy on Fly

By Dj Walker-Morgan GitHub Twitter

<%= partial "/docs/partials/obsolete_doc" %>

Everything starts with a Fly app on Fly. If you already have an application running somewhere else, and want to get some of the benefits of running it close to users, you can launch a proxy app on Fly. This will forward requests to your origin application for processing.

Configuring NGINX

NGINX is a powerful HTTP proxy server you can use to direct traffic to its appropriate destination, apply routing rules, or even implement caching. We start with a Dockerfile that'll allow us to create a NGINX image with our own nginx.conf configuration file:

FROM nginx
COPY nginx.conf /etc/nginx/conf.d/nginx.conf

That's it. It copies a local configuration file into the image. In this example config, we want to proxy requests from example.com to realexample.com and proxy requests from exemplum.com to realexemplum.com.

server {
  listen 8080;
  listen [::]:8080;

  server_name example.com;

  location / {
      proxy_pass https://realexample.com/;
      proxy_set_header X-Forwarded-Host $http_host;
  }
}

server {
  listen 8080;
  listen [::]:8080;

  server_name exemplum.com;

  location / {
      proxy_pass https://realexemplum.com/;
      proxy_set_header X-Forwarded-Host $http_host;
  }
}

Both server sections are set to listen on port 8080. The server_name directive says which hostname the server directive will be handling and the location directive uses proxy_pass to send all requests on to the appropriate site.

Deploying NGINX to Fly

We now need to create a slot for our new Fly app. Assuming you are signed up and logged in (if not see our hands-on for getting started), then we'll run this:

flyctl apps create

This command will prompt us for an app name - we'll use nginxproxy but we recommend you use the autogenerated name to ensure a unique name. As well as creating the slot for the app in the Fly infrastructure, a fly.toml file will be created with the app name and configuration settings in it. To deploy our NGINX, we literally issue the deploy command:

flyctl deploy

Our app will now be built and deployed onto the Fly infrastructure. When that's complete, get the status of the application with flyctl status. You'll see it has a hostname which you can use to connect. The host name will match none of the hosts in the nginx.conf file and so it will proxy for the default server - the first server listed in that configuration file.

Choose Your Own Adventure

With the proxy app in place, you now have a foundation for adding features "at the edge". Maybe try HTTP caching in NGINX, or look at our OpenResty guide and learn to write Lua. Or if you're feeling extra spicey, let your customers add their own domains to your application.