title: psycopg2.OperationalError: could not translate host name to address using psycopg2 and docker
body: <p>I've been trying for a few hours now but no solution from similar asked questions seem to work for me...
  I am using docker-compose to setup a postgresql database and run a python webserver from where I want to connect to my postgressql database (so it's running inside the container)</p>
  <pre class="lang-yaml prettyprint-override"><code>version: '3.8'
  
  services:
    database:
      container_name: database
      hostname: database
      image: postgres
      restart: always
      environment:
        POSTGRES_DB: mydatabase
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: password
      volumes:
        - postgres:/pgdata
        - ./application/ressources/fixtures.sql:/docker-entrypoint-initdb.d/fixtures.sql 
      ports:
        - &quot;5432:5432&quot;
  
    application:
      container_name: application
      build: .
      ports:
        - &quot;5001:5001&quot;
      volumes: 
        - ./application:/application
      restart: always
      depends_on:
        - database
  
  volumes:
      postgres:
  </code></pre>
  <p>I trying to connect as follows ( I have read that despite the <strong>depends on</strong> in my dockerfile the database needs some more time until it can accept connections so i added a retry logic):</p>
  <pre class="lang-py prettyprint-override"><code>
          retries = 0
          while retries &lt; 5:
              retries = retries + 1
              self.conn = psycopg2.connect(user='postgres', password='password',
                                           host='database', port=&quot;5432&quot;, database='mydatabase')
              if not self.conn:
                  logging.info(&quot;retry to connect&quot;)
                  sleep(5)
  </code></pre>
  <p>The weird thing is that when running it with <strong>docker-compose -f docker-compose.yml up</strong> everything works fine.
  But when I built the image (<strong>docker build -t myapp:0.1</strong>) and run it (<strong>docker run myapp:0.1</strong>) it gives me the following error:</p>
  <pre><code>File &quot;/application/libraries/database.py&quot;, line 18, in establishConnection
      self.conn = psycopg2.connect(user=CONFIG.DATABASE_USER, password=CONFIG.DATABASE_PASSWORD,
    File &quot;/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py&quot;, line 127, in connect
      conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
  psycopg2.OperationalError: could not translate host name &quot;database&quot; to address: Name or service not known
  </code></pre>
  <p>I've read that when using docker-compose a single network is created, so this can't be the error here i guess <a href="https://docs.docker.com/compose/networking/" rel="nofollow noreferrer">Docker Compose doku</a></p>
  <p>Thanks in advance,
  Jacky</p>