0

In my docker-compose file I have a frontend, backend and Database. If I start docker-compose up the backend starts before the Database are finished, so they crashed because the backend can not connect to any database.

server_backend:
build:
  context: server_backend
ports:
  - 8080:8080
links: 
  - database
depends_on:
  - database
restart: unless-stopped



database:
    image: mysql
    ports:
      - 3306:3306

I use "depends_on:" but it do not help.

How can I say, that the backend should created after the database?

1 Answers1

0

You will need to either:

  • Add code to your backend image that waits for the database to become available before starting your backend application, or

  • Add code to your backend application that will retry the database connection if it fails.

The first option is the simplest to implement, while the second option is more robust (because it will, for example, allow your backend application to continue if you were to restart the database container).

An implementation of the first option may be as simple as the following shell script (modified to included the appropriate connection credentials):

while ! mysql -h database -e 'select 1' mydatabase; do
    sleep 1
done

This will repeatedly try to connect to the database and execute a sql command. It will loop until the sql command executes successfully. You would place this, for example, in an ENTRYPOINT script in your backend image (or as part of an application startup script).

larsks
  • 277,717
  • 41
  • 399
  • 399