Starting crystal in production mode
Asked Answered
E

2

6

I've been running my Crystal webapp by building it, and then running the executable. However, it always listens on port 3000.

How do I build/run Crystal webapps listening on 80 and 443?

I'm using Kemal as well. Here is my sample app.

require "kemal"

get "/" do
  "Hello World!"
end

Kemal.run

Building:

crystal build src/myapp.cr

Running:

./myapp
Escapee answered 17/2, 2018 at 20:53 Comment(0)
S
8

Simply pass a port to Kemal.run:

require "kemal"

get "/" do
  "Hello World!"
end

port = ARGV[0]?.try &.to_i?
Kemal.run port

Build:

crystal build src/myapp.cr

Run:

./myapp # default port 3000
./myapp 80
./myapp 443
Subequatorial answered 17/2, 2018 at 21:0 Comment(2)
Please be aware that binding to a privileged port (port number < 1024) usually requires superuser rights. And for running in a production environment you'll probably need some kind of service management to ensure the application availability.Sexcentenary
@Vitalii Elenhaupt building Kemal application with --release flag doesn't guarantee running it in production mode. It will still run in development mode with release level optimization. One way to run it in production mode is to use KEMAL_ENV=production variable either export it in system environment or use with your Kemal executable as KEMAL_ENV=production ./myapp 80Stonefish
P
1

First, make sure you build your binary in release mode:

crystal build --release src/myapp.cr

To overwrite the port and binding (e.g. 0.0.0.0), you can use this example configuration:

Kemal.config.port = (ENV["PORT"]? || 8080).to_i
Kemal.config.host_binding = ENV["HOST_BINDING"]? || "127.0.0.1"
Kemal.config.env = "production"
Kemal.config.powered_by_header = false

Notes:

  • Instead of overwriting Kemal.config.env, you can also enable production mode by setting KEMAL_ENV=production ./myapp.
  • Disabling powered_by_header is optional. It is not a security risk in itself, but revealing what kind of server you are running could help an attacker. Thus, the recommendation is to avoid all unnecessary information. It will also slightly reduce traffic to omit the header. However, when troubleshooting a system, including the header can be beneficial.
Patroclus answered 28/4, 2020 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.