Search code examples
clojuredockercompojuredockerfile

How to get Clojure Compojure app to run headless via compiled jar within Docker container?


Update: this question has changed since the original set of commenters left responses. Apologies for any confusion.


This is my code repository https://github.com/Integralist/spurious-clojure-example you can use it as an example for what I'm working with.

Note that the above repo relies on a library I've not yet published to Clojars (as I'm still testing it - hence this question opened). You can see the source code of the library here: https://github.com/Integralist/spurious-clojure-aws-sdk-helper

I have a "hello world" Clojure web app written with Compojure that I have working fine when run using lein ring server and lein run (as I have a -main function now created). It also runs to a certain extent when compiled down into a jar and I run java -jar app.jar.

My problem now is that if I try to run the default java -jar app.jar from within a Docker container I get the following error telling me...

spurious-clojure-example is starting
2015-02-14 00:58:03.812:INFO:oejs.Server:jetty-7.x.y-SNAPSHOT
2015-02-14 00:58:03.854:INFO:oejs.AbstractConnector:Started [email protected]:8080
Started server on port 8080
Exception in thread "main" java.awt.HeadlessException:

My code is currently using a -main function like so...

(ns spurious-clojure-example.repl
  (:use spurious-clojure-example.handler
        ring.server.standalone
        [ring.middleware file-info file])
  (:gen-class))

(defonce server (atom nil))

(defn get-handler []
  (-> #'app
    (wrap-file "resources")
    (wrap-file-info)))

(defn start-server
  "used for starting the server in development mode from REPL"
  [& [port]]
  (let [port (if port (Integer/parseInt port) 8080)]
    (reset! server
            (serve (get-handler)
                   {:port port
                    :init init
                    :auto-reload? true
                    :destroy destroy
                    :join true}))
    (println (str "You can view the site at http://localhost:" port))))

(defn stop-server []
  (.stop @server)
  (reset! server nil))

(defn -main []
  (start-server))

...but how do I get the server to start headless? I can't quite follow the Compojure boilerplate code to decipher where or how it knows when to run headlessly or via browser?

I know that on the command line you can do lein ring server-headless so what's the programmatic equivalent of that?


Solution

  • Because ring-server is primarily meant for development, it tries to open a browser when the server starts. This fails with a java.awt.HeadlessException on platforms without a GUI. You'll want to set the :open-browser? option to false to prevent this.