How to NOT start two servers on the same port

11 June 2018   2 comments   Linux, Web development

First of all, you can't start two servers on the same port. Ultimately it will fail. However, you might not want a late notice of this. For example, if you do this:

# In one terminal
$ cd elasticsearch-6.1.0
$ ./bin/elasticsearch
$ curl localhost:9200
"version" : {
    "number" : "6.1.0",
# In *another* terminal
$ cd elasticsearch-6.2.4
$ ./bin/elasticsearch
$ curl localhost:9200
"version" : {
    "number" : "6.1.0",

In other words, what happened to the elasticsearch-6.2.4/bin/elasticsearch?? It actually started on port :9201. But that's a rather scary thing because as you jump between project in different tabs or you might not notice that you have Elasticsearch running with docker-compose somewhere.

To remedy this I use this curl one-liner:

$ curl -s localhost:9200 > /dev/null && echo "Already running!" && exit || ./bin/elasticsearch

Now if you try to start a server on a used port it will exit early.

To wrap this up in a script, take this:


set -eo pipefail

curl -s "$hostandport" >/dev/null && \
  echo "Already running on $hostandport" && \
  exit 1 || exec "$@"

...and make it an executable called and now you can do this:

$ localhost:9200 ./bin/elasticsearch


Sascha Welter

But the real problem here is that elasticsearch goes to a different port without asking or giving feedback.

That is pretty braindead behaviour for any kind of server process. When it does that, how are the clients going to guess that this happened? No sane server should do that.

Peter Bengtsson

Yeah, it's really odd. Why would that ever be useful?!

Your email will never ever be published

Related posts

GeneratorExit - How to clean up after the last yield in Python 07 June 2018
How to unset aliases set by Oh My Zsh 14 June 2018
Related by Keyword:
redirect-chain - Getting a comfortable insight input URL redirects history 14 February 2020
elapsed function in bash to print how long things take 12 December 2018
How I found out where a bash alias was set up 09 May 2018
Run something forever in bash until you want to stop it 13 February 2018
When Docker is too slow, use your host 11 January 2018