title: FastAPI, asyncpg (postgres) and Docker: wsocket.gaierror: [Errno -3] Temporary failure in name resolution
body: <p>I'm aware that the error I'm about to describe is disgustingly generic, but I'm days into debugging and getting nowhere...</p>
  <p>I'm running a fastapi application in docker, using the library <code>fastapi-users</code>, which uses <code>sqlalchemy==1.4</code> and <code>asyncpg</code>. My database interface is based in this file:</p>
  <pre class="lang-py prettyprint-override"><code>from typing import AsyncGenerator
  
  from fastapi import Depends
  from fastapi_users.db import SQLAlchemyBaseUserTable, SQLAlchemyUserDatabase
  from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
  from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
  from sqlalchemy.orm import sessionmaker
  
  from backend.models.user import UserDB
  from backend.core.settings.config import settings
  
  Base: DeclarativeMeta = declarative_base()
  
  
  class UserTable(Base, SQLAlchemyBaseUserTable):
      pass
  
  
  DATABASE_URL = &quot;postgresql+asyncpg://ubuntu:secrets@app-db:5432/app_db&quot;
  
  
  engine = create_async_engine(DATABASE_URL)
  async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
  
  
  async def create_db_and_tables():
      async with engine.begin() as conn:
          await conn.run_sync(Base.metadata.create_all)
  
  
  async def get_async_session() -&gt; AsyncGenerator[AsyncSession, None]:
      async with async_session_maker() as session:
          yield session
  
  
  async def get_user_db(session: AsyncSession = Depends(get_async_session)):
      yield SQLAlchemyUserDatabase(UserDB, session, UserTable)
  </code></pre>
  <p>Then I spin up the app using this docker-compose setup:</p>
  <pre class="lang-yaml prettyprint-override"><code>version: '3.5'
  
  services:
    # PostgreSQL development environment database
    app-db:
      image: postgres:12-alpine
      volumes:
        - pgdata:/var/lib/postgresql/data
      environment:
        POSTGRES_USER: ubuntu
        POSTGRES_PASSWORD: secrets
        POSTGRES_DB: app_db
      ports:
        - &quot;5432:5432&quot;
  
  
    # FastAPI backend
    app-backend:
      build:
        context: ./backend
      depends_on:
        - app-db
      ports:
        - &quot;8000:8000&quot;
      stop_signal: SIGINT
      command: uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000
      environment:
        PYTHONPATH: .
        BASE_ENVIRONMENT: prod
  </code></pre>
  <p>The database is created okay, and the app starts up, but when I go to create the tables in my <code>main.py</code> file:</p>
  <pre class="lang-py prettyprint-override"><code>async def create_db_and_tables():
      async with engine.begin() as conn:
          await conn.run_sync(Base.metadata.create_all)
  
  @app.on_event(&quot;startup&quot;)
  async def on_startup():
      await create_db_and_tables()
  </code></pre>
  <p>the whole thing blows up and the tables are not created:</p>
  <pre class="lang-sh prettyprint-override"><code> INFO:     Started server process [8]
  app-backend_1   | INFO:     Waiting for application startup.
  app-backend_1   | ERROR:    Traceback (most recent call last):
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/starlette/routing.py&quot;, line 621, in lifespan
  app-backend_1   |     async with self.lifespan_context(app):
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/starlette/routing.py&quot;, line 518, in __aenter__
  app-backend_1   |     await self._router.startup()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/starlette/routing.py&quot;, line 598, in startup
  app-backend_1   |     await handler()
  app-backend_1   |   File &quot;/ubuntu/./backend/main.py&quot;, line 26, in on_startup
  app-backend_1   |     await create_db_and_tables()
  app-backend_1   |   File &quot;/ubuntu/./backend/db.py&quot;, line 24, in create_db_and_tables
  app-backend_1   |     async with engine.begin() as conn:
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/ext/asyncio/base.py&quot;, line 60, in __aenter__
  app-backend_1   |     return await self.start(is_ctxmanager=True)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/ext/asyncio/engine.py&quot;, line 596, in start
  app-backend_1   |     await self.conn.start(is_ctxmanager=is_ctxmanager)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/ext/asyncio/engine.py&quot;, line 155, in start
  app-backend_1   |     await (greenlet_spawn(self.sync_engine.connect))
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py&quot;, line 134, in greenlet_spawn
  app-backend_1   |     result = context.throw(*sys.exc_info())
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/future/engine.py&quot;, line 406, in connect
  app-backend_1   |     return super(Engine, self).connect()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 3210, in connect
  app-backend_1   |     return self._connection_cls(self, close_with_result=close_with_result)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 96, in __init__
  app-backend_1   |     else engine.raw_connection()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 3289, in raw_connection
  app-backend_1   |     return self._wrap_pool_connect(self.pool.connect, _connection)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/engine/base.py&quot;, line 3256, in _wrap_pool_connect
  app-backend_1   |     return fn()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 310, in connect
  app-backend_1   |     return _ConnectionFairy._checkout(self)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 868, in _checkout
  app-backend_1   |     fairy = _ConnectionRecord.checkout(pool)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 476, in checkout
  app-backend_1   |     rec = pool._do_get()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py&quot;, line 146, in _do_get
  app-backend_1   |     self._dec_overflow()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py&quot;, line 70, in __exit__
  app-backend_1   |     compat.raise_(
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/compat.py&quot;, line 207, in raise_
  app-backend_1   |     raise exception
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py&quot;, line 143, in _do_get
  app-backend_1   |     return self._create_connection()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 256, in _create_connection
  app-backend_1   |     return _ConnectionRecord(self)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 371, in __init__
  app-backend_1   |     self.__connect()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 666, in __connect
  app-backend_1   |     pool.logger.debug(&quot;Error on connect(): %s&quot;, e)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py&quot;, line 70, in __exit__
  app-backend_1   |     compat.raise_(
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/compat.py&quot;, line 207, in raise_
  app-backend_1   |     raise exception
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/pool/base.py&quot;, line 661, in __connect
  app-backend_1   |     self.dbapi_connection = connection = pool._invoke_creator(self)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/engine/create.py&quot;, line 590, in connect
  app-backend_1   |     return dialect.connect(*cargs, **cparams)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/engine/default.py&quot;, line 597, in connect
  app-backend_1   |     return self.dbapi.connect(*cargs, **cparams)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py&quot;, line 777, in connect
  app-backend_1   |     await_only(self.asyncpg.connect(*arg, **kw)),
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py&quot;, line 76, in await_only
  app-backend_1   |     return current.driver.switch(awaitable)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py&quot;, line 129, in greenlet_spawn
  app-backend_1   |     value = await result
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/connection.py&quot;, line 2085, in connect
  app-backend_1   |     return await connect_utils._connect(
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/connect_utils.py&quot;, line 895, in _connect
  app-backend_1   |     raise last_error
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/connect_utils.py&quot;, line 881, in _connect
  app-backend_1   |     return await _connect_addr(
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/connect_utils.py&quot;, line 781, in _connect_addr
  app-backend_1   |     return await __connect_addr(params, timeout, True, *args)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/connect_utils.py&quot;, line 825, in __connect_addr
  app-backend_1   |     tr, pr = await compat.wait_for(connector, timeout=timeout)
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/compat.py&quot;, line 66, in wait_for
  app-backend_1   |     return await asyncio.wait_for(fut, timeout)
  app-backend_1   |   File &quot;/usr/local/lib/python3.9/asyncio/tasks.py&quot;, line 479, in wait_for
  app-backend_1   |     return fut.result()
  app-backend_1   |   File &quot;/home/ubuntu/.local/lib/python3.9/site-packages/asyncpg/connect_utils.py&quot;, line 691, in _create_ssl_connection
  app-backend_1   |     tr, pr = await loop.create_connection(
  app-backend_1   |   File &quot;/usr/local/lib/python3.9/asyncio/base_events.py&quot;, line 1026, in create_connection
  app-backend_1   |     infos = await self._ensure_resolved(
  app-backend_1   |   File &quot;/usr/local/lib/python3.9/asyncio/base_events.py&quot;, line 1405, in _ensure_resolved
  app-backend_1   |     return await loop.getaddrinfo(host, port, family=family, type=type,
  app-backend_1   |   File &quot;/usr/local/lib/python3.9/asyncio/base_events.py&quot;, line 861, in getaddrinfo
  app-backend_1   |     return await self.run_in_executor(
  app-backend_1   |   File &quot;/usr/local/lib/python3.9/concurrent/futures/thread.py&quot;, line 58, in run
  app-backend_1   |     result = self.fn(*self.args, **self.kwargs)
  app-backend_1   |   File &quot;/usr/local/lib/python3.9/socket.py&quot;, line 954, in getaddrinfo
  app-backend_1   |     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  app-backend_1   | socket.gaierror: [Errno -3] Temporary failure in name resolution
  app-backend_1   | 
  app-backend_1   | ERROR:    Application startup failed. Exiting.
  </code></pre>
  <p>So I've got this <code>socket.gaierror: [Errno -3] Temporary failure in name resolution</code> error, related for some reason to an SSL issue (<code>_create_ssl_connection</code>?), even though I'm not trying to create an SSL connection, or do anything beyond running the app at <code>localhost:8000</code>.</p>
  <p><strong>The app and database work fine locally if I don't use Docker.</strong></p>
  <p>Any advice?</p>