title: How to autogenerate and apply migrations with alembic when the database runs in a container?
body: <p>I find the workflow for working with database migrations in a containerized environment confusing. I have a web API with an attached database. The API runs in one container and the database in another. The project file structure is as follows</p>
  <pre><code>.
  ├── docker-compose.yml
  ├── Dockerfile
  └── app
  |    ├── __init__.py
  |    ├── database
  |    |    ├── alembic/
  |    |    ├── __init__.py
  |    |    ├── db.py
  |    |    └── models.py
  |    ├── other
  |    ├── source
  |    └── files
  ├── other
  └── files
  </code></pre>
  <p>In order for the API container to be able to access the database the sqlalchemy.url in the ini-file is set to:</p>
  <p><code>postgresql://{username}:{password}@db:5432/{database}</code></p>
  <p>However when I want to do a migration, for example add a table column, I will change the model in <code>app/database/models.py</code> change directory to <code>app/database</code> and run <code>alembic revision --autogenerate -m &quot;Description&quot;</code>. This is where the problem occurs, I get the error:</p>
  <pre><code>sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name &quot;db&quot; to address: Name or service not known
  </code></pre>
  <p>If I change the hostname to localhost it works but then the docker-compose breaks since it has to reference the container name.</p>
  <p>This workflow does not seem right. How do people work with databases in projects which uses containers?</p>
  <p>The <code>docker-compose.yml</code> file looks like this:</p>
  <pre class="lang-yaml prettyprint-override"><code>version: &quot;3&quot;
  
  services:
    db:
      image: postgres
      ports:
        - &quot;5432:5432&quot;
      environment:
        - POSTGRES_USER=username
        - POSTGRES_PASSWORD=password
        - POSTGRES_DB=database
  
    app:
      build: .
      command: bash -c &quot;cd app/database &amp;&amp; alembic upgrade head &amp;&amp; cd ../.. &amp;&amp; python app/main.py&quot;
      volumes:
        - .:/code
      ports:
        - &quot;5000:5000&quot;
      depends_on:
        - db
  </code></pre>