2022-10-13
DeployFlyDomainSsl

How to point your domain to a Phoenix site on Fly.io

Fly.io gives you a temporary domain so you can access your site during development. But sooner or later, you want to point a real domain to your Phoenix site. In a previous post, I went through the process of deplying to Fly.io. Since I have a domain for my new project, I want to make sure that that domain is pointed to my app instead of the development domain.

This post goes through how you can do that in a few simple steps.

Step 1 - find out where to point the domain

if I log into my app on Fly.io, I can see it on the overview.

In my case, its an IP-version 4 number like this one:

123.66.29.123

Step 2 - Point the A-record to that domain

When you have located the IP number, you can login to your domain dashboard and add the IP as an A-record

Note, this can take up to an hour before it takes effect. Sometimes even longer. So don't assume that you have made a mistake.

Step 3 - Add a certificate in Fly dashboard

Since I want to enforce SSL on the webtraffic, I need to create an SSL certificate in the Fly dashboard. That is a neat service provided for free and Fly makes sure to renew the certificate.

Start with entering the domain in the certificates page and press create.

When I press create, I get some additional instructions for DNS settings that I need to add in my domain providers dashboard:

Step 4 - Code changes and deploy

Last step here is to make sure that my site responds to the new domain. The only changes that I need to do is in the config/runtime.exs file.

  host = "liveview.build"
  port = String.to_integer(System.get_env("PORT") || "4000")

  config :screen_builder, ScreenBuilderWeb.Endpoint,
    force_ssl: [rewrite_on: [:x_forwarded_proto]],
    url: [host: host, port: 443, scheme: "https"],
    http: [
      # Enable IPv6 and bind on all interfaces.
      # Set it to  {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
      # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html
      # for details about using IPv6 vs IPv4 and loopback vs public addresses.
      ip: {0, 0, 0, 0, 0, 0, 0, 0},
      port: port,
      compress: true,
    ],
    secret_key_base: secret_key_base

I need to change the host to "liveview.build", port to 443 and scheme to "https". There is also the line force_ssl: [rewrite_on: [:x_forwarded_proto]], that is there to forwars unsecure http requests to https.

Last thing I need to do now it to visit my new URL and make sure everything works:

Great success!!