title: Docker and Django. django.db.utils.OperationalError: could not connect to server
body: <p>I can't find solution, please help!</p>
  <p>I have <strong>Dockerfile</strong></p>
  <pre><code>FROM python:3
  
  ENV PYTHONUNBUFFERED=1
  
  RUN mkdir /app
  WORKDIR /app
  
  RUN pip install Django \
      &amp;&amp; pip install psycopg2 \
      &amp;&amp; pip install jinja2 \
      &amp;&amp; pip install Pillow
  
  COPY . /app/
  </code></pre>
  <p>And <strong>docker-compose.yaml</strong></p>
  <pre><code>version: &quot;3&quot;
  
  services:
    db:
      image: postgres
      environment:
        - POSTGRES_DB=folivora
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
      ports:
        - 5432:5432
  
    site:
      image: folivora:latest
      command: bash -c &quot;python manage.py migrate &amp;&amp; python manage.py runserver 0.0.0.0:8000&quot;
      volumes:
        - .:/app
      depends_on:
        - db
      ports:
        - 8000:8000
  </code></pre>
  <p>And <strong>settings.py</strong></p>
  <pre><code>DATABASES = {
  'default': {
      'ENGINE': 'django.db.backends.postgresql_psycopg2',
      'NAME': 'folivora',
      'USER': 'postgres',
      'PASSWORD': 'postgres',
      'HOST': 'db',
      'PORT': '5432',
  }
  </code></pre>
  <p>}</p>
  <p>And <strong>ERROR</strong> when run &quot;docker-compose up&quot;</p>
  <pre><code>site_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
  site_1  |   Is the server running on host &quot;db&quot; (192.168.224.2) and accepting
  site_1  |   TCP/IP connections on port 5432?
  </code></pre>
  <p>When I edit docker-compose.yaml, change string command to:</p>
  <pre><code>command: bash -c &quot;python manage.py runserver 0.0.0.0:8000&quot;
  </code></pre>
  <p>all is fine. So, migration line broke my code, but i don't know why.</p>
  <p>I try to create empty django project to check the same config. On first &quot;docker-compose up&quot;, all started and working fine, but from second start, all is broke again with the same error. Over time this problem gone from test project, I dont know why, maby cache or something...</p>
  <p><strong>New info</strong></p>
  <ol>
  <li><p>Run <code>docker-compose up</code> with command <code>command: bash -c &quot;python manage.py runserver 0.0.0.0:8000&quot;</code> in docer-compose.yaml and catch error.</p>
  </li>
  <li><p>Then Ctrl+C (exit from docker compose &quot;shell&quot;) but don't do <code>docker-compose down</code>, because this command delete created container.</p>
  </li>
  <li><p>Run <code>docker-compose up</code> with command <code>command: bash -c &quot;python manage.py migrate &amp;&amp; python manage.py runserver 0.0.0.0:8000&quot;</code> in docer-compose.yaml and all is successfull started.</p>
  </li>
  </ol>
  <p>I think it is bad solution.</p>