Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker wait for postgresql to be running

I am using postgresql with django in my project. I've got them in different containers and the problem is that i need to wait for postgres before running django. At this time i am doing it with sleep 5 in command.sh file for django container. I also found that netcat can do the trick but I would prefer way without additional packages. curl and wget can't do this because they do not support postgres protocol. Is there a way to do it?

like image 671
Quba Avatar asked Jan 28 '16 18:01

Quba


People also ask

How can I tell if Postgres is running?

basically just type "systemctl status postgresql-xx" where xx is the version of your PostgreSQL instance. ex: systemctl status posgresql-10.

What is the use of Docker wait command?

The 'docker wait' is a command that is used to wait or block until one or more containers stop, and then it outputs their exit codes which means you cannot use your terminal if you are running the command on the terminal.


2 Answers

I've spent some hours investigating this problem and I got a solution. Docker depends_on just consider service startup to run another service. Than it happens because as soon as db is started, service-app tries to connect to ur db, but it's not ready to receive connections. So you can check db health status in app service to wait for connection. Here is my solution, it solved my problem. :) Important: I'm using docker-compose version 2.1.

version: '2.1'  services:   my-app:     build: .     command: su -c "python manage.py runserver 0.0.0.0:8000"     ports:        - "8000:8000"     depends_on:       db:         condition: service_healthy     links:       - db     volumes:       - .:/app_directory    db:     image: postgres:10.5     ports:       - "5432:5432"     volumes:       - database:/var/lib/postgresql/data     healthcheck:       test: ["CMD-SHELL", "pg_isready -U postgres"]       interval: 5s       timeout: 5s       retries: 5  volumes:   database: 

In this case it's not necessary to create a .sh file. I hope it helps you guys ;) cya

like image 84
Vinicius Chan Avatar answered Sep 18 '22 14:09

Vinicius Chan


This will successfully wait for Postgres to start. (Specifically line 6). Just replace npm start with whatever command you'd like to happen after Postgres has started.

services:   practice_docker:      image: dockerhubusername/practice_docker     ports:        - 80:3000     command: bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; npm start'     depends_on:       - db     environment:       - DATABASE_URL=postgres://postgres:password@db:5432/practicedocker       - PORT=3000      db:     image: postgres     environment:       - POSTGRES_USER=postgres       - POSTGRES_PASSWORD=password       - POSTGRES_DB=practicedocker 
like image 34
Alister Avatar answered Sep 18 '22 14:09

Alister