Home > other >  docker one of the containers shuts down immediately
docker one of the containers shuts down immediately

Time:11-28

I'm trying to learn Docker, and I'm trying to create a simple CRUD application using MariaDB and Go. I created a Dockerfile for Go:

FROM golang:1.17

WORKDIR /src/app

COPY . .

# RUN go get -u github.com/go-sql-driver/mysql \
#     go get -u github.com/gin-gonic/gin

RUN go build -o app .

CMD [ "./app" ]

And I also have a docker-compose so I can start MariaDB container and the Go container:

version: '3.8'

services:
  db:
    container_name: appdb
    image: mariadb:latest
    volumes:
      - ./dbdata:/var/lib/mysql/data
    environment:
      MYSQL_ROOT_PASSWORD: "1234"
      MYSQL_DATABASE: "crudapp"
      MYSQL_USER: "root"
      MYSQL_PASSWORD: "root"
  
  app:
    container_name: crudapi
    build:
      context: .
    ports:
      - '8080:8080'
    depends_on:
      - db

When I run docker-compose up the appdb container starts, but the crudapi does not. It seems like it starts and then shuts down, because I have exit code 0 in the console. I search the web but couldn't figure out why this is happening. I saw I should try and add tty:true to the docker-compose file but it also didn't work.

What am I doing wrong here?

CodePudding user response:

depends_on does not wait for the db to be ready before starting your app, so on startup Compose does not wait until a container appdb is “ready” (whatever that means for your particular application) - only until it’s running.

In practice, you have to implement a check in your application code, both at startup and whenever a connection is lost for any reason and you can also include a wait-for like tool.

CodePudding user response:

Container won't wait for db to start. You have to add the Timeout in your app. Or implement logic for checking in for loop till the db container is started up.

Or you can use the script described here - Docker control startup script

  • Related