Search code examples
clojureleiningenring

How to set ring port based on profile


I have a clojure ring project and I want to be able to set the port number based on the profile. Currently I have the following snippet from project.clj

:plugins [[lein-ring "0.8.13"]]
:ring {:handler project.handler/webServer
       :init    project.init/initialize
       :port    80}
:profiles {:dev        {:jvm-opts ["-Dproperty-file=dev.properties"]}
           :ci         {:jvm-opts ["-Dproperty-file=ci.properties"]}
           :uberjar    {:aot :all}})

What I would like to do is to set the port to 8080 for development environments and then port 80 for the production environment. I would run on port 80 all the time but that requires root privilege and not something I want to do for a dev run. I have tried (blindly) to put the ring port into the uberjar profile but that didn't work. I also tried to use the environ project to set the ring port based on the environment variable but that didn't work either.

I am open to a solution that passes command line arguments to the java -jar [...]-standalone.jar command but I am stuck on how to get any approach to work.


Solution

  • You don't need environ. Use it when you need to access configuration variables in the source code. In project.clj you could directly do this:

    :profiles {:dev        {:jvm-opts ["-Dproperty-file=dev.properties"]
                            :ring {:port 8080}}
               :ci         {:jvm-opts ["-Dproperty-file=ci.properties"]
                            :ring {:port 80}}
               :uberjar    {:aot :all
                            :ring {:port 80}}})
    

    I have tested this (without jvm-opts and port 8081 instead of 80) and it works.

    Alternative: if they are different machines, you could use the OS's environment variables:

    :ring {:handler project.handler/webServer
           :init    project.init/initialize
           :port    ~(System/getenv "RING_PORT")}
    

    And then set RING_PORT to 8080 in your dev machine and 80 on the production machine.

    $ export RING_PORT=80