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:

#!/bin/bash

set -eo pipefail

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

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

$ unlessalready.sh localhost:9200 ./bin/elasticsearch

Comments

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

Previous:
GeneratorExit - How to clean up after the last yield in Python 07 June 2018
Next:
How to unset aliases set by Oh My Zsh 14 June 2018
Related by Keyword:
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
Synonyms with elasticsearch-dsl 05 December 2017
A neat trick to zip a git repo with a version number 01 September 2017
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
I'm Prolog 01 May 2007
Ever wondered how much $87 Billion is? 04 November 2003