Docker-compose depends on not waiting until depended on service isn't fully started

 ̄綄美尐妖づ 提交于 2020-01-11 13:21:16

问题


version: '3'
services: 
server:
  container_name: hotel-server
  build: 
    dockerfile: Dockerfiles/server/Dockerfile
    context: .
  environment:
    dbhost: db
  links: 
    - db
  depends_on:
    - db
  restart: always
  ports: 
    - "3456:3456"

db:
  image: "custom-postgis:latest"
  container_name: hotelsdb
  environment:
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: alliswell
    # POSTGRES_DB: hotels

  ports: 
    - "5437:5432"
  volumes: 
    - hoteldata:/var/lib/postgresql/data #persistence
volumes: 
hoteldata: {}

The way I've set up the custom-postgis, its a custom postgres database container that has some initialization scripts which I have to wait until it starts. The problem is the server service starts before the db service fully starts.

Is there any workaround to that?


回答1:


Is there any workaround to that?

Yes.

First, realize that depends-on is almost entirely useless. Docker doesn't know anything about your application; it has no way to tell that your database server isn't actually ready to service requests.

The correct solution is to code your application so that (a) it will retry the initial database connection until it is ready, and (b) it will reconnect to the database if the connection should fail. (a) solves the problem you're asking about, and (b) allows you to restart the database container independent of the application container.

If you don't control the code in your application container, you can wrap your main command with a shell script that does something like:

while ! psql -c 'select 1'; do
  sleep 1
done

(Setting appropriate authentication options or setting up a .pgpass file)



来源:https://stackoverflow.com/questions/59472638/docker-compose-depends-on-not-waiting-until-depended-on-service-isnt-fully-star

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!