About docker container’s exit when docker-compose up

I’m trying to use Elasticsearch with docker.

And you can see the guide here -> https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html

my docker-compose.yml below

version: '2.2'
services:
  elasticsearch1:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: elasticsearch1
    environment:
      - node.name=master-node
      - cluster.name=es-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - es-data01:/usr/share/elasticsearch/data
    ports:
      - 127.0.0.1:9200:9200
      - 127.0.0.1:9300:9300
    networks:
      - elastic
    stdin_open: true
    tty: true

  elasticsearch2:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: elasticsearch2
    environment:
      - node.name=data-node1
      - cluster.name=es-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - "discovery.zen.ping.unicast.hosts=elasticsearch1"
    ports:
      - 127.0.0.1:9301:9300
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - es-data02:/usr/share/elasticsearch/data
    networks:
      - elastic
    stdin_open: true
    tty: true

volumes:
  es-data01:
    driver: local
  es-data02:
    driver: local

networks:
  elastic:
   # driver: bridge

the problem is

  1. I cannot connect by curl -XGET localhost:9200
  2. docker container exits automatically after few seconds

can you help me?

ps : when I try docker run it works. what is the difference between them?

docker run -d -p 9200:9200 -p 9300:9300 --name elasticsearch -it --rm -v els:/usr/share/elasticsearch/data -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.7.0

Source: StackOverflow