0

Elasticsearch create index using docker compose

I would like to set elasticsearch locally using docker-compose.yaml file with default index products.

My docker-compose.yaml file looks like this:

version: '3.1'

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.0
    container_name: es
    environment:
      - discovery.type=single-node
    ports:
      - 9200:9200
    deploy:
      resources:
        limits:
          memory: 2GB

How can I create index on elasticsearch during running docker compose up -d instead of creating it manually?

mikolaj semeniuk
  • 2,030
  • 15
  • 31
  • 1
    Might this be useful? https://stackoverflow.com/questions/35526532/how-to-add-an-elasticsearch-index-during-docker-build – FabioStein Mar 14 '23 at 00:47

1 Answers1

1

To complement what was commented by @FabioStein about the related stackoverflow question, if for whatever reason you don't want an additional dockerfile but keep everything in your docker-compose file, you can use the command option. E.g.,

version: '3.1'

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.0
    container_name: es
    environment:
      - discovery.type=single-node
    ports:
      - 9200:9200
    command: >
      bash -c '
        until curl -sS "http://localhost:9200/_cat/health?h=status" | grep -q "green\|yellow"; do
          sleep 1
        done
        curl -X PUT "http://localhost:9200/products" -H "Content-Type: application/json" -d'
        {
          "mappings": {
            "properties": {
              "name": { "type": "text" },
              "quantity": { "type": "integer" }
            }
          }
        }'
      '
    deploy:
      resources:
        limits:
          memory: 2GB

Anyhow, this is less elegant and maintainable than a separated dockerfile, but, you know, just for the records

glenacota
  • 2,314
  • 1
  • 11
  • 18