Tag Archives: elasticsearch

What is Docker and how to use it ?

I must admit that it took me some time to really understand what is Docker and the concepts behind it.

Docker logo

This post’s goal is to share my experience with people who heard of Docker and would like to know more about it, or understand it better.

Docker’s website describes it as “an open-source engine that automates the deployment of any application as a lightweight, portable, self-sufficient container that will run virtually anywhere.”.

This may be a bit abstract at first, so I’ll try to explain what Docker is (and is not) from my developer point of view :

  • Docker is built on top of LXC, and thereforce runs containers, not VMs as Virtualbox for instance

  • Docker containers are made of portable “images”, similar to LXC/VZ templates, but much more powerful (versionning, inheritance …)

  • Docker “images” can easily be created via Dockerfile’s, where are set the base image and the steps to run in order to create your image

  • Docker allows to have run multiple instances of your container without needing to copy the image (base system) files

  • Docker daemon (which manages / runs LXC containers) provides a REST API used by Docker CLI utility … but this REST API can be used by any application (read doc here)

  • Docker runs on virtually all operating systems (Linux, Mac OS, Windows …) and platforms (Google Cloud Platform, Amazon EC2) : read more about installing Docker

Oh, and I forgot to tell you Docker is developed in Go (see sources on GitHub) !

Let’s run our first containers

Once you’ve installed Docker on your computer, you can now create your first container (check that docker -d is running) :

$ sudo docker run ubuntu /bin/echo hello world

If you see “hello world”, that’s it !

So, you may be wondering, what is this docker run command actually doing ?

First, it downloads the necessary Ubuntu image (keep this keyword in mind) to run your container.

Then, it creates a container running the Ubuntu image, “starts it” and runs the supplied command (/bin/echo hello world) and prints the output, before “stopping” it.

Note that Docker actually did a lot more, but let’s keep it simple for now (see “Run ‘hello world‘” section here).

docker run command accepts many command-line options, let’s have a quick look at some very useful ones :

  • -d : run container in detached mode, printing the resulting container id

  • -i : keep stdin open, ie. when you want to take control of a shell within the container

  • -t : allocate a pseudo-tty (useful when running a shell)

  • -name : specify container’s name ; usage : -name myubuntu

  • -w : set current working directory inside the container (create it if not present) ; usage : -w /some/path/

  • -expose : expose a specified port in container’s network interface ; usage : -expose <port-number>

  • -p : forward a port from from host to container ; usage : -p (will bind local port 8080 to container’s port 80)

Running your container with shell command as argument, in detached mode, will give a similar behavior as a regular LXC :

$ sudo docker run -d -i -t ubuntu /bin/bash

This command should output the newly created container id. You may also get it (in it’s short version) running sudo docker ps (only active containers are shown, use -a option to show all) :

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
ecd101259f8f        ubuntu:12.04        /bin/bash           2 seconds ago       Up 2 seconds                            focused_franklin

Focused franklin” container is up and running Ubuntu 12.04 since 2 seconds ! Try to attach it :

$ sudo docker attach <your-container-id>

Install “ping” utility (yes, image really is a bare Ubuntu) running apt-get update && apt-get install ping net-tools, and try to ping www.google.com. Wow, network is already fully working, you can see details with a simple ifconfig.

Exit (and stop) the container by pressing CTRL+D or typing exit.

You might also want to get some more informations about any of your container or image by running :

$ sudo docker inspect <container-id>

Cleaning up

If you wish to clean / remove all the Docker containers you’ve created, run this line (this will remove all your existing containers) :

$ sudo docker ps -a | grep ^[0-9a-f] | cut -d " " -f 1 | xargs sudo docker rm

Images, containers …

So far, you may still be wondering what’s the difference between images and containers (see this Wikipedia article about OS-level virtualization if you are not familiar with containers).

In my opinion, images are what make Docker a really powerful and interesting tool.

Think of Docker images as the evolved version of LXC/OpenVZ templates : an image is a read-only layer, containing an operating system with some applications for instance, on top of which your container will be built (with its own read-write layer).

Very important thing to keep in mind : images can never be altered. Each change made to an image actually creates a new image that references the one it’s been built from.

This offers a nice inheritance system : you can create & maintain images that reference each other. For example, this Elasticsearch image in Docker index references a Java image, which references a custom Ubuntu image, on top of the Docker’s base Ubuntu image. See the power of Docker ?

You can even visualize this with little help of Graphviz’s dot utility ; I pulled both ubuntu:latest and debian:wheezy images, here is the images graph that I get :

See, even Debian and Ubuntu image reference a same base image !


Let’s say you create an image based on Ubuntu, and add (install) PHP in it, a new image will be created with base Ubuntu image as parent (see explicit schemas at Docker.io).

Any container using this newly created image will therefore be made of 3 layers :

  • Container’s read-write layer

  • “PHP install” image’s read-only layer

  • Ubuntu image’s read-only layer

This union of read-only/read-write layers is called Union File System.

Within the container, no changes can be made on the images files : these actually create a copy of the modified file(s) inside the container’s read-write layer.

You can use the docker diff command to view added (A) / changed (C) / deleted (D) files in your container’s read-write layer, in comparison with it’s image. Here’s an example :

$ sudo docker diff <container-id>
C /dev
A /dev/kmsg
C /tmp
C /tmp/hsperfdata_root
C /usr
C /usr/share
C /usr/share/elasticsearch
A /usr/share/elasticsearch/data
A /usr/share/elasticsearch/data/elasticsearch
A /usr/share/elasticsearch/data/elasticsearch/nodes
A /usr/share/elasticsearch/data/elasticsearch/nodes/0
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/_state
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/_state/global-3
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/_state
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/_state/state-4
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/index
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/index/_checksums-1391120105322
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/index/segments.gen
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/index/segments_4
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/translog
A /usr/share/elasticsearch/data/elasticsearch/nodes/0/indices/index/0/translog/translog-1391119827027

Creating an image with container’s changes

You made changes in your container and would like to save the result as an image ? Nothing simpler to do with the docker commit command.


Last but not least, images have tags, allowing you to identify a specific version of an image.

For instance, base Ubuntu image has 3 tags (versions) available : latest (default), quantal (12.10) and precise (12.04).

You can specify which tag you want to use by using this syntax : image:tag (ie. docker pull ubuntu:latest).

Docker images index

When you begin using Docker, you’ll pull (more on docker pull command) images from the main Docker index, browseable through https://index.docker.io/ (and docker search command).

You can also use private repositories (on top of your own/private Docker registry) : read more about private repositories in the official documentation.

The Dockerfile

You have several ways to build your custom image. I already talked about the “docker commit” way (see above), let’s talk about the Dockerfile way.

A Dockerfile simply is a set of instructions to run over a base image. Docker will build an image from your Dockerfile, which will result in a final image.

Note that an intermediate image is built after each instruction is ran, so you can revert to any step of the build process.

Elasticsearch Dockerfile sample

Let’s take a sample Dockerfile that simply install and runs Elasticsearch on a base Debian Wheezy image, in which I commented each line :

# You must specify a base image ; in this example,
# tag wheezy of image debian will be pulled
# from Docker’s public repository
FROM        debian:wheezy
# Who maintains this Dockerfile
MAINTAINER  Michael BOUVY <michael.bouvy@gmail.com>
# Each RUN command creates a new version of your image.
# We use it here to install necessary tools / applications
# needed by Elasticsearch
RUN         apt-get update && DEBIAN_FRONTEND=noninteractive apt-get -y install adduser openjdk-7-jre-headless
# Download the Elasticsearch DEB file into /tmp
# Prefer using this method instead of downloading
# (ie. with wget) the file, so Docker can cache it
ADD        https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.10.deb /tmp/elasticsearch.deb
# And install it with RUN command
RUN         dpkg -i /tmp/elasticsearch.deb
# Expose port of container
EXPOSE      9200
# Default command to run within container
CMD         ["/usr/share/elasticsearch/bin/elasticsearch", "-f"]

The resulting image is available in Docker Index and the source Dockerfile on GitHub.

As you can see, each line is a couple of an instruction (RUN, CMD, etc.) and it’s arguments.

Let’s now build a container from our newly created Dockerfile :

$ sudo docker build -t elasticsearch .

And run it (in detached mode) :

$ sudo docker run -d elasticsearch

Note the container ID, and get it’s IP address :

$ sudo docker inspect <container-id> | grep IPAddr | cut -d "\"" -f 4

Try to reach http://<container-ip-address>:9200 in your browser, you should see Elasticsearch’s output.

Collect & visualize your logs with Logstash, Elasticsearch & Redis

Update of December 6th : although Logstash does the job as a log shipper, you might consider replacing it with Lumberjack / Logstash Forwarder, which needs way less resources, and keep Logstash on your indexer to collect, transform and index your logs data (into ElasticSearch) : check out my latest blog post on the topic.

Kibana Dashboard

Kibana Dashboard

Even if you manage a single Linux server, you probably already know how hard it is to keep an eye on what’s going on with your server, and especially tracking logs data. And this becomes even worse when you have several (physical or virtual) servers to administrate.

Logstash logo

Although Munin is very helpful monitoring various informations from my servers / VMs, I felt the need of something more, and bit less static / more interactive.

There are 3 kind of logs I especially wanted to track :

  • Apache 2 access logs
  • iptables logs
  • Syslogs

After searching arround on the internet for a great tool that would help me, I read about the open source log management tool Logstash which seems to perfectly suit a (major) part of my needs : logs collecting / processing.

For the purpose of this post, I will take the following network architecture and assume and I want to collect my Apache, iptables, system logs from servers 1/2/3 (“shippers”) on server 4 (“indexer”) and visualize them :

Logstash architecture

As you can see, I am using 4 complementary applications, the role of each one being :

  • Logstash : logs collector, processor and shipper (to Redis) on log “shippers” 1-3 ; logs indexer on server 4 (reads from Redis, writes to Elasticsearch)
  • Redis : logs data broker, receiving data from log “shippers” 1-3
  • Elasticsearch : logs data persistent storage
  • Kibana : (time-based) logs data visualization (graphs, tables, etc.)


As shown on the schema above, I will describe how to install all of Logstash + Redis + Elasticsearch + Kibana on the same “indexer” server. You may want to separate these on different servers for any reason, just set the correct IPs / hostnames accordingly, in the examples below.



First of all, let’s install Redis on our indexer server (right, that’s #4 on the schema). As the versions of Redis available in Linux distributions repositories are not up to date, we’ll download the last stable release from Redis’ website :

$ sudo aptitude install gcc
$ wget http://download.redis.io/releases/redis-2.6.16.tar.gz
$ tar xzf redis-2.6.16.tar.gz
$ cd redis-2.6.16
$ make MALLOC=libc
$ sudo cp src/redis-server /usr/local/bin/
$ sudo cp src/redis-cli /usr/local/bin/

Launch redis-server (sudo redis-server), try to ping Redis to see if server is working :

$ redis-cli ping

If you get a PONG reply, your Redis server works fine. You might want to install Redis more properly, if so, follow this excellent guide at Redis.io.

You’re now ready to ship logs data from your servers to Redis. Note that Redis listens on it’s default port (tcp/6379) and accepts incoming connections from any IP :

$ netstat -tanpu|grep redis
tcp   0   0*   LISTEN   16955/redis-server

Logstash (shippers)

You will need to set an instance of Logstash on each of your servers you want to collect data from, it will act as a “logs shipper”.

Open a shell on one of the servers you want to collect log data from, and dowload logstash.

$ sudo mkdir /opt/logstash /etc/logstash
$ sudo cd /opt/logstash
$ sudo wget https://download.elasticsearch.org/logstash/logstash/logstash-1.2.2-flatjar.jar

Create a Logstash config file in /etc/logstash :

input { stdin { } }
output { stdout { codec => rubydebug } }

Now launch the logstash agent and type something, you should get something like this :

$ java -Xmx256m -jar logstash-1.2.2-flatjar.jar agent -f logstash-test.conf
hello world
  "message" => "hello world",
  "@timestamp" => "2013-11-17T18:35:56.672Z",
  "@version" => "1",
  "host" => "myhostname"

Logstash works fine, let’s configure it to work with our previously-installed Redis instance. Create a new config file :

input { stdin { } }
output {
  stdout { codec => rubydebug }
  redis { host => "" data_type => "list" key => "logstash" }

You’ll of course need to replace “” by the IP of your server Redis is running on.

Launch logstash agent with logstash-redis.conf as config file and type something as above. Then, on your indexer server (where Redis is installed), launch redis-cli :

redis> LLEN logstash
(integer 1)
redis> LPOP logstash
"{\"message\":\"hello redis\",\"@timestamp\":\"2013-11-17T20:35:13.910Z\",\"@version\":\"1\",\"host\":\"myhostname\"}"

Here it is, we’ve got our message transmitted by Logstash to our Redis server. You’ve probably noticed that Logstash added a few fields to our initial (minimalistic) data (@timestamp, @version and host).

Now that we’ve got Logstash able to send data to Redis, we can begin processing our Apache 2 and iptables logs.

Apache 2 logs processing

Create a new config file in /etc/logstash :

input {
  file {
    path => "/var/log/apache2/*access.log"
    type => "apache"

filter {
  if [type] == "apache" {
    grok {
      pattern => "%{COMBINEDAPACHELOG}"

output {
  redis { host => "" data_type => "list" key => "logstash" }

This config is quite self-explanatory ; few things although :

  • type => “apache” allows us to use conditionals further
  • pattern => “%{COMBINEDAPACHELOG}” is a built-in regex-like used to match against our Apache logs lines and extract fields (request, host, response, etc.)

Launch the logstash agent, and you’re done. It’s that simple ! You should now see the logstash list count grow in Redis (LLEN logstash) as your Apache gets hits.

iptables logs processing

There is no built-in grok pattern available to extract data from iptables logs, but there’s one available in Logstash’s cookbook config snippets.

Create a directory where you will keep your custom grok patterns (i.e. /usr/share/grok/patterns) and create a new file called iptables :

# Source : http://cookbook.logstash.net/recipes/config-snippets/
ETHTYPE (?:(?:[A-Fa-f0-9]{2}):(?:[A-Fa-f0-9]{2}))
IPTABLES1 (?:IN=%{WORD:in_device} OUT=(%{WORD:out_device})? MAC=%{NETFILTERMAC} SRC=%{IP:src_ip} DST=%{IP:dst_ip}.*(TTL=%{INT:ttl})?.*PROTO=%{WORD:proto}?.*SPT=%{INT:src_port}?.*DPT=%{INT:dst_port}?.*)
IPTABLES2 (?:IN=%{WORD:in_device} OUT=(%{WORD:out_device})? MAC=%{NETFILTERMAC} SRC=%{IP:src_ip} DST=%{IP:dst_ip}.*(TTL=%{INT:ttl})?.*PROTO=%{INT:proto}?.*)

You’ll also need to declare this directory in Logstash’s config file (see below). Now let’s process our iptables logs, create or edit a logstash config file :

input {
  file {
    path => [ "/var/log/syslog" ]
    type => "iptables"

filter {
  if [type] == "iptables" {
    grok {
      patterns_dir => "/usr/share/grok/patterns/iptables"
      pattern => "%{IPTABLES}"

output {
  # Check that the processed line matched against grok iptables pattern
  if !("_grokparsefailure" in [tags]) {
    redis { host => "" data_type => "list" key => "logstash" }

Actually, despite the very useful Grok Debugger, I couldn’t get these this pattern working. Plus, you will have to guess one way or another wether the log line is a REJECT, DROP, ACCEPT or whatever.

To make this simpler, you may use iptables rules like this :

iptables -N LogAndDrop
iptables -A LogAndDrop -p tcp -j LOG --log-prefix "RULE 1 -- DROP " --log-level=info
iptables -A LogAndDrop -j DROP

You can also create rules for REJECT / ACCEPT rules following this one.

Good thing is that your iptables log lines will now be prefixed with a “DROP” (or REJECT / ACCEPT), allowing you to process these log lines in a different way, measuring ACCEPT vs. DROP/REJECT count for instance. Here is the grok pattern you can use :

IPTABLES (.*RULE \d? -- (%{WORD:action})?.*SRC=(%{IP:src_ip}).*DST=(%{IP:dst_ip}).*PROTO=(%{WORD:protocol}).*SPT=%{INT:src_port}?.*DPT=%{INT:dst_port}?.*)

The following fields will be extracted for you iptables logs :

  • action = depending on what you set in your custom iptables rules, may be REJECT, DROP, ACCEPT …
  • src_ip = source IP address
  • dst_ip = destination IP address
  • protocol = protocol (TCP, UDP, ICMP, etc.)
  • src_port = source port number
  • dst_port = destination port number

You’ll probably notice that not all the data available in the logs is exctracted, feel free to adapt the grok pattern upon your specific needs.

Note that if you decide to create a “log & accept” iptables rule, it’s definitely NOT a good idea to systematically use it instead of the regular ACCEPT one. You’d rather use it to track connections from specific IP addresses ranges for example.

system logs (syslog) processing

Edit your existing one or create a new Logstash config file :

input {
  file {
    path => [ "/var/log/*.log", "/var/log/messages", "/var/log/syslog" ]
    type => "syslog"

output {
  redis { host => "" data_type => "list" key => "logstash" }

As each log line may have a different format, they will each be stored “as is” in the “message” field in Elasticsearch. Anyway, this will not prevent you from analyzing this data (by example getting the number of (un)successful authentications from auth.log).


Thanks to a Debian package available on Elasticsearch’s official download page, a few command lines only will be sufficient to get it up and running :

$ sudo aptitude install openjdk-7-jre-headless
$ wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.7.deb
$ sudo dpkg -i elasticsearch

Elasticsearch should have started automatically, open your browser and reach http://yourhostname:9200/. If everything wen fine, you should get a JSON response looking like this :

  "ok": true,
  "status": 200,
  "name": "Alibar",
  "version": {
    "number": "0.90.7",
    "build_hash": "36897d07dadcb70a865b7f149e645ed3d44eb5f2",
    "build_timestamp": "2013-11-13T12:06:54Z",
    "build_snapshot": false,
    "lucene_version": "4.5.1"
  "tagline": "You Know, for Search"

If necessary, you can tune Elasticsearch’s run parameters in /etc/default/elasticsearch and configuration parameters in /etc/elasticsearch/[elasticsearch,logging].yml.

Note for OpenVZ users

After (too much) hours of searching and trying various configurations, I still couldn’t get my Elasticsearch running in an OpenVZ Debian container, or more precisely, it won’t listen for incoming (HTTP) connections on it’s default port 9200 (visible process, but nothing with netstat).

It actually seems to be a common issue with Java running in an OpenVZ container, and I finally found a solution in this post from OpenVZ forums.

In short, edit your CT config file (usually /etc/vz/conf/CTID.conf), comment out the CPUS line and add a CPULIMIT line as following :

# CPUS="1"

(Re)start your container, Elasticsearch should now work fine.

Logstash (indexer)

Thanks to a comment from DJP78, I realized that I forgot to explain how to configure Logstash on the indexer side : pulling logs data from Redis and storing them into Elasticsearch.

Here is the Logstash config you can use (note that I also process local [indexer] system logs) :

input {
  file {
    type => "syslog"
    path => [ "/var/log/*.log", "/var/log/messages", "/var/log/syslog" ]
  redis {
    host => ""
    data_type => "list"
    key => "logstash"
    codec => json
output {
  elasticsearch { bind_host => "" }

You can check if Logstash is correctly doing his job on the indexer, by either watching the list size decrease in Redis (redis-cli and then LLEN logstash) or searching your Elasticsearch index via a HTTP GET request : http://yourElasticSearchHostname:9200/_search?q=_index%20like%20logstash%25&sort=@timestamp:desc.


Finally, let’s install Kibana. Kibana is a modern & dynamic (AngularJS based) frontend for Logstash / Elasticsearch, allowing you to get charts, tables, etc. from your collected logs data.


All you need to use Kibana is a HTTP web server and access to Elasticsearch’s port 9200 (from your browser).

It’s installation is quite straight-forward :

$ sudo aptitude install git
$ cd /var/www
$ git clone https://github.com/elasticsearch/kibana.git kibana

Now open http://yourhostname/kibana/ in your browser. Tada !

Note that if Elasticsearch is not installed on the same server (or available through the same hostname) as Elasticsearch, you’ll need to configure it’s hostname (and possibly port) in config.js at Kibana’s root.

On first launch, Kibana offers you to use a “Logstash dashboard”, click on the link. You can now see your logs data in a table, try to activate some useful fields in the left column, or create your first graph :-).


  • Download Logstash on all your “shippers” and your “indexer”
  • Install and launch Redis on your “indexer”
  • Install and launch Elasticsearch on your “indexer”
  • Clone Kibana git repository on your “indexer” in /var/www
  • Create Logstash config files for your shippers and indexer (see above), launch all Logstash instances