top of page

Headless IB Gateway in Docker: Restarts, 2FA, Reconnects

4 minutes ago
14 min read
Headless IB Gateway in Docker: daily restarts, 2FA and reconnects cover

AI Summary: A headless IB Gateway setup runs Interactive Brokers’ Java desktop Gateway in Docker with IBC handling logins and Xvfb providing a virtual display. Keeping it alive takes more than the container: a planned daily auto-restart, a weekly full login with two-factor authentication after IBKR resets security tokens on Sunday, reconnect and reconciliation logic in your application, resting exit orders at the broker, and alerts that wake a human only when needed.


If you automate trading on Interactive Brokers (IBKR), sooner or later you hit the same wall: Interactive Brokers’ IB Gateway was built for a person sitting at a screen. It’s a Java desktop app. It restarts itself every day, asks for a full login with two-factor authentication every week, and drops your API connection at the worst moments. Getting a headless IB Gateway running in Docker is the easy part. Keeping it alive for months without anyone touching it is the real work.


We run IB Gateway headless in production for a multi-account options desk. Orders go out at market open, profit-target exits rest at the broker, and nobody watches the Gateway. This guide covers what it took: the container, the IBC settings that matter, the daily restart, the honest truth about 2FA, the reconnect logic in the application, the alerts, and which Python client to use.


Key takeaways


  1. Start from a maintained IB Gateway Docker image (IBC + Xvfb included). Don’t build your own.

  2. Set AutoRestartTime, ExistingSessionDetectedAction=primary, ReadOnlyLogin=no and a writable API (ReadOnlyApi=no) in IBC.

  3. Expect a weekly full re-authentication and plan for it.

  4. Your app needs its own reconnect loop, a reconciliation pass after every reconnect, and an escalation path that halts trading.

  5. Keep exits as resting GTC orders at IBKR so a disconnect never leaves a position unprotected.

  6. Use ib_async, the maintained successor to ib_insync. In our tests on Python 3.14, ib_insync fails as soon as it is imported.


Why Interactive Brokers’ IB Gateway is hard to run headless


IB Gateway is a lighter version of Trader Workstation (TWS) that exposes the TWS API on a local socket. It’s the standard way to connect a Python, Java or C# trading system to IBKR. But it carries its desktop roots with it:


  • It needs a display. It’s a Java GUI with no true headless mode, so on a server it has to run against a virtual framebuffer (Xvfb).

  • It needs a login. Without help, someone has to type a username and password into a window.

  • It restarts every day. TWS and IB Gateway insist on a daily restart. You choose the time, or the Gateway chooses for you.

  • It re-authenticates weekly. IBKR invalidates the security tokens every Sunday at 1:00 a.m. ET, so the next login needs a full username, password and second factor again.

  • 2FA is mandatory. IBKR’s API documentation states that two-factor authentication is required for all users, so old guides that assume it’s switched off are out of date.

  • It allows one session per username. IBKR doesn’t let the same username log in to several trading applications at once. If a second session appears, for example after an unclean shutdown or when you open TWS on a laptop, one of them gets kicked off.


Every one of these is fine for a person and a failure mode for a bot. The fix is to treat the Gateway as unreliable infrastructure and build three layers around it.


The three layers of a reliable headless IB Gateway setup


Layer

Job

Tools

1. Container

Run the Gateway with no screen and no human login

Docker image with IB Gateway + IBC + Xvfb

2. Session lifecycle

Daily restart, weekly re-auth, 2FA, session conflicts

IBC settings, a scheduled restart window, a 2FA strategy

3. Application resilience

Survive drops, never trade blind, tell a human

Reconnect loop, reconciliation, heartbeat, alerts, kill switch


Most tutorials stop at layer 1. Production failures happen in layers 2 and 3.


Step 1. Start from a maintained IB Gateway Docker image


Use a community-maintained IB Gateway Docker image rather than writing your own Dockerfile from scratch. IBC’s login and restart handling has been used by automated traders for many years, and its lineage (IBController) goes back more than two decades. Rebuilding it is wasted effort in the flakiest part of your stack.


We build on gnzsnz/ib-gateway, which bundles IB Gateway, IBC, Xvfb, an optional VNC server and socat, and tracks IBKR’s stable and latest release channels. You don’t need a Dockerfile of your own: the image generates IBC’s config.ini from environment variables at start-up, so all of our settings live in docker compose (Step 3).


Pin the stable channel, not latest. The latest channel picks up new Gateway builds first. For a system that trades real money, predictable beats new. In production, pin an exact version tag rather than the moving stable tag, and upgrade deliberately. In November 2026 the image’s stable channel was IB Gateway 10.50 with IBC 3.24.2.


Note on IBC’s status. IBC’s author retired the project on 1 September 2026. The IBC repository is now archived: releases can still be downloaded and significant bugs may still be fixed, but no new development is planned. Factor that into your upgrade testing, because a future Gateway change may need an IBC fix that isn’t coming.


Xvfb and VNC


Xvfb gives the Java GUI a virtual screen. Most images also include a VNC server so you can see what the Gateway is showing: login dialogs, error pop-ups, a stuck 2FA prompt. In the gnzsnz image, VNC only starts if you set a VNC password. Turn it on for local development only. In production, never publish the VNC port. If you need to look, use an SSH tunnel.


Step 2. Configure IBC for unattended operation


IBC (formerly IBController) automates the Gateway’s login and keeps it running. It reads a config.ini with dozens of settings. You only need to override a handful. These are the ones that matter for unattended trading:


IBC setting (image env var)

Our value

Why

AutoRestartTime (AUTO_RESTART_TIME)

11:45 PM, with the Gateway time zone set to America/New_York

You choose when the daily restart happens, outside your trading hours, instead of letting it happen at an arbitrary time while a position is open. IBC expects the time in hh:mm AM/PM format.

ExistingSessionDetectedAction (EXISTING_SESSION_DETECTED_ACTION)

primary

IBC’s docs say a primary session can’t be overridden by a new login, and it reconnects automatically if another session tells it to end. That stops a stray login with the same username from quietly knocking your bot offline.

ReadOnlyLogin

no

With yes, IBC skips the second factor and logs in read-only, where placing or managing orders isn’t allowed. Keep it no so a login problem fails loudly instead of producing a session that can’t trade.

ReadOnlyApi (READ_ONLY_API)

no

IBKR enables the Read-Only API setting by default, and it blocks all API orders. Set it explicitly for a fresh container.

TradingMode (TRADING_MODE)

via env var (paper / live)

Set by the container at start, so the same image runs paper and live.


If you run IBC yourself (or set the image’s CUSTOM_CONFIG=yes and mount your own file), the equivalent config.ini overrides are:


; ibc/config.ini (overrides only)
; Never put IbLoginId / IbPassword here. They come from env vars or secrets.
ExistingSessionDetectedAction=primary
ReadOnlyLogin=no
ReadOnlyApi=no
AutoRestartTime=11:45 PM

Single-instance rule. Session settings don’t stop two copies of your trading app from connecting to the same Gateway and sending the same order twice. We enforce exactly one trading process with a PostgreSQL advisory lock that the trading app takes at startup and holds for its whole lifetime. A second copy fails to get the lock and exits before it can connect to IBKR or place an order.


Step 3. Wire it into docker compose safely


Keep the Gateway on a private Docker network with no published API port, and inject credentials from a secrets manager at runtime. The API socket is effectively root access to your brokerage account.


services:
  app:
    build: { context: ., dockerfile: docker/Dockerfile.app }
    env_file: .env              # sourced from your secrets manager in prod
    depends_on: [ibgateway]
    networks: [internal]
    restart: unless-stopped

  ibgateway:
    image: ghcr.io/gnzsnz/ib-gateway:stable   # pin an exact version tag in production
    environment:
      TWS_USERID: ${IBKR_USERNAME}
      TWS_PASSWORD_FILE: /run/secrets/ibkr_password
      TRADING_MODE: ${IBKR_TRADING_MODE}   # paper | live
      READ_ONLY_API: "no"
      AUTO_RESTART_TIME: "11:45 PM"
      TIME_ZONE: America/New_York
      EXISTING_SESSION_DETECTED_ACTION: primary
      TWS_SETTINGS_PATH: /home/ibgateway/tws_settings
    secrets: [ibkr_password]
    networks: [internal]        # no API port published to the host, ever
    restart: unless-stopped
    volumes:
      - ibgateway_settings:/home/ibgateway/tws_settings   # keeps Gateway settings across restarts

networks:
  internal: { driver: bridge }

volumes:
  ibgateway_settings:

secrets:
  ibkr_password:
    file: ./secrets/ibkr_password.txt   # or your secrets manager's integration

Your app connects to the Gateway by its service name (ibgateway) on the internal network. The standard API ports are:


Application

Live port

Paper port

IB Gateway

4001

4002

Trader Workstation (TWS)

7496

7497


Inside a container, the Gateway only accepts connections from its own localhost, so images relay the API with socat. In the gnzsnz image, socat exposes the Gateway’s 4001 (live) and 4002 (paper) on container ports 4003 and 4004, so an app on the same Docker network connects to ibgateway:4004 for paper. Check your image’s README. A cheap safety net: make the app refuse to start against a live port unless live trading is explicitly enabled in config.


The IB Gateway daily restart and weekly re-authentication


IB Gateway restarts once a day by design, and needs a full login with two-factor authentication once a week. With AutoRestartTime set, IBC’s auto-restart brings the Gateway back after the daily restart without a new login: the Gateway closes, comes back, and restores the session. Your API client is disconnected for that window and has to reconnect on its own.


The weekly cycle is different. IBKR’s auto-restart guidance says auto-restart requires manual authentication once a week, because the security tokens are invalidated each Sunday at 1:00 a.m. ET. IBC’s documentation suggests a Sunday “cold restart” after that time to trigger the full login. Plan for it rather than fight it:


  • Pick a restart time well outside the hours your strategy trades.

  • Schedule a “Gateway ready?” check before the first session of the week, and alert loudly if it fails (see Health checks below).

  • Never assume the connection survived the night. Check it explicitly every morning.


Handling IB Gateway 2FA without a human at the screen


This is where most guides are wrong or out of date. The honest summary: how much of 2FA you can automate depends on which second factor your IBKR login uses.


  • IB Key (push to the IBKR Mobile app): someone has to approve on a phone. IBC can select the right device and, if the approval times out, restart the login to give you another chance, but it can’t approve for you. Treat the weekly login as a scheduled human task and alert the person on call when the prompt appears.

  • A six-digit code from an authenticator app: IBKR offers a TOTP-based Mobile Authenticator option to eligible users (eligibility is regional). The code can be generated on the server from the enrolment secret and typed into the Gateway’s “Second Factor Authentication” dialog. That is what our watcher does. IBKR’s TWS API page on supported 2FA methods doesn’t list Mobile Authenticator, so test it against your own Gateway login on a paper account first. Also note that only the most recently activated authenticator for a username produces valid codes.


Our watcher is a small Python process that polls the Xvfb display, finds the dialog by its window title, computes the current RFC 6238 code, and types it in. Three lessons cost us real debugging time:


  • Java Swing ignored synthetic X events sent to a window. xdotool type --window <id> did nothing for us. Focus the field with a real click, then type with XTest (xdotool type with no --window).

  • Clear the field before typing, and wait a few hundred milliseconds between click, clear, type and OK. The dialog lags behind the input.

  • Cool down after submitting (we wait 15 seconds) so the watcher doesn’t see the closing dialog and submit a stale code a second time.


import subprocess, time

def find_2fa_window(display=":99"):
    r = subprocess.run(
        ["xdotool", "search", "--onlyvisible", "--name", "Second Factor"],
        capture_output=True, text=True, env={"DISPLAY": display},
    )
    ids = r.stdout.split()
    return ids[0] if ids else None

def watch(secret, display=":99", poll=2.0):   # use your image's DISPLAY value
    while True:
        wid = find_2fa_window(display)
        if wid:
            code = totp_now(secret)           # RFC 6238, 30s step, 6 digits
            submit_code(wid, code, display)   # click field, clear, XTest type, OK
            time.sleep(15)                    # let the dialog close
        time.sleep(poll)

Security trade-off. If your server holds both the password and the 2FA secret, your login is effectively single-factor again for anyone who compromises that server. If you choose this route: keep the TOTP secret in a secrets manager (never in .env files or the image), restrict who can reach the host, keep the Gateway off the public internet, and alert on every automated login. Check IBKR’s terms for your account type. Many teams decide the weekly human approval is worth keeping.


Surviving IB Gateway disconnects in your application


Your trading app must assume the Gateway connection will drop and handle reconnection itself. The daily restart guarantees at least one disconnect a day, and network blips add more. IBKR reports connection state through message codes on the API’s error callback:


Code

Meaning

What your app should do

1100

Connectivity between IBKR and TWS / IB Gateway has been lost

Stop sending new orders. Start the reconnect/escalation clock. Alert after a short debounce.

1101

Connectivity restored, data lost

Resubscribe all market data, then reconcile orders and positions.

1102

Connectivity restored, data maintained

Reconcile orders and positions. Subscriptions are intact.

2110

Connectivity between TWS/Gateway and the server is broken; it will be restored automatically

Same as 1100. Treat as degraded.

2104 / 2106 / 2158

Market data / historical data / sec-def farm connection OK

Informational. Log at debug, don’t alert.

2172

The application version will be desupported; upgrade to a newer version

Schedule an upgrade (see below). Alert once.


Separately from these codes, your socket to the Gateway itself can disappear, for example during the nightly restart. We handle that with a simple polling loop that runs next to the trading loop:


# ib here is our thin wrapper around ib_async.IB
async def connection_loop(ib, max_retries, poll_seconds=60):
    failures = 0
    while True:
        try:
            if not ib.is_connected():
                failures += 1
                try:
                    await ib.connect()
                    failures = 0
                except Exception:
                    log.exception("reconnect failed (%s/%s)", failures, max_retries)
                    if failures >= max_retries and not await trading_halted():
                        await halt_trading(reason="ibkr_relogin_failed")  # once per outage
                        await alert("IBKR relogin failed. Trading halted.")
            await write_heartbeat(connected=ib.is_connected())
            if ib.is_connected():
                await reconcile()   # open orders, executions, positions vs our DB
        except Exception:
            log.exception("loop iteration failed; retrying next cycle")
        await asyncio.sleep(poll_seconds)

Three design choices make this hold up in production:


  • Escalate once per outage. After N failed attempts, halt trading and alert, but check the halted flag first so a long outage doesn’t produce an alert every minute.

  • Reconcile after every reconnect. Fills can happen while you’re disconnected. Pull open orders and executions from IBKR and compare them with your database before you trust local state. We go deeper on this, including fills that arrive with orderId = 0, in our guide to reconciling fills against IBKR’s records.

  • Keep exits at the broker. Place the profit-target exit as a resting GTC order at IBKR as soon as the entry fills. If your app or the Gateway goes down, the exit still works. Exit logic that lives only in application memory is the most expensive bug in this field.


Health checks and alerts you will actually read


Good alerting is quiet when nothing’s wrong and impossible to miss when something is. What worked for us:


  • Heartbeat table. Every loop cycle writes connected / disconnected with a timestamp to the database. The dashboard and the health monitor both read it.

  • Debounced disconnect alerts. Alert only after about two minutes of continuous disconnect (four 30-second polls). The nightly restart and short blips stay silent.

  • Pre-market readiness checks. At 45 and 15 minutes before the open, check the Gateway session, the market-data feed and the halt flag. Send a red alert if anything’s wrong, and a single green “ready” message at T-15 if everything’s fine.

  • Restart-proof deduplication. Record sent notifications in the database, not in memory, so a process restart doesn’t resend the morning alert.

  • Never trade stale data. Refuse signals older than a set age, and alert when the market-data feed stops updating, even if the socket still looks connected.

  • A kill switch a human can reach from a phone. Telegram commands for halt and resume, audited like every other action.


Which Python client? Use ib_async


If you connect to IB Gateway from Python, use ib_async, the maintained successor to ib_insync. ib_insync is no longer updated. In our tests on Python 3.14, a plain import of ib_insync fails with RuntimeError: There is no current event loop in thread 'MainThread'. ib_async connects normally, and for most code the migration is a rename of the imports.


We cover the error, the migration diff and what to retest in ib_insync vs ib_async on Python 3.14: the error and the fix.


Upgrading IB Gateway without breaking production


IBKR periodically retires old Gateway versions. You’ll first see message 2172, telling you the version you run will be desupported and that you should upgrade. Treat it as a scheduled weekend job, not an emergency:


  • Stay on the stable channel, and upgrade on a weekend with the market closed.

  • Back up the Gateway settings directory (jts.ini and your settings volume). Upgrades can reset API settings such as the socket port and trusted IPs.

  • Set time-in-force explicitly on every API order (DAY for entries, GTC for resting exits), so changes to GUI defaults in new builds can’t touch your orders.

  • Retest reconciliation after every upgrade, and filter open orders by status explicitly rather than assuming what a request returns.


Production checklist


  • Maintained IB Gateway Docker image on the stable channel, version pinned

  • IBC: AutoRestartTime outside trading hours, ExistingSessionDetectedAction=primary, ReadOnlyLogin=no, ReadOnlyApi=no

  • Credentials and any 2FA secret injected from a secrets manager at runtime

  • API port never published; VNC only through an SSH tunnel

  • Exactly one trading process, enforced by a lock

  • App refuses live ports unless live mode is explicitly enabled

  • Reconnect loop with once-per-outage escalation that halts trading

  • Reconciliation after every reconnect

  • Exits rest at IBKR as GTC orders the moment an entry fills

  • Heartbeat, debounced disconnect alerts, pre-market readiness checks

  • Stale-signal and stale-feed guards

  • Phone-reachable kill switch, every action audited

  • ib_async pinned and tested against paper on your Python version

  • Weekend upgrade runbook for Gateway desupport warnings


FAQ


Can IB Gateway run headless?

Not natively. IBKR says headless (GUI-less) operation of TWS or IB Gateway isn’t supported, because both expect a login window. On a server it runs against a virtual display (Xvfb), with IBC handling the login. Docker images such as gnzsnz/ib-gateway bundle all three, which is the closest you can get to a headless IB Gateway.

What ports does IB Gateway use?

IB Gateway listens on port 4001 for live trading and 4002 for paper trading by default. Trader Workstation uses 7496 (live) and 7497 (paper). Some Docker images expose the API through socat on different ports (the gnzsnz image uses 4003 and 4004 inside the container), so check your image’s documentation.

Why does IB Gateway disconnect every day?

TWS and IB Gateway require a daily restart. With IBC’s AutoRestartTime you choose when it happens, and the auto-restart comes back without a new login, except for the weekly full login. Your API client still loses its connection during the restart and must reconnect on its own.

Can I automate IB Gateway two-factor authentication?

Partly. If your login uses IB Key push approval, a person has to approve on the phone, usually once a week. If it uses a six-digit authenticator code, a watcher process can generate and enter the code, but storing that secret on the server weakens your second factor, so protect it carefully.

What do IBKR error codes 1100, 1101 and 1102 mean?

1100 means the Gateway lost its connection to IBKR’s servers. 1101 means the connection is back but market data subscriptions were lost and must be resubscribed. 1102 means the connection is back and data was kept. After either 1101 or 1102, reconcile orders and positions.

How do I keep IB Gateway running 24/7?

Run it in a container with IBC, set AutoRestartTime to a quiet hour, and let your application reconnect on its own after each restart. Add a heartbeat, a debounced disconnect alert and a pre-market readiness check. Plan for one full login with two-factor authentication each week, after IBKR invalidates security tokens on Sunday at 1:00 a.m. ET.

Should I use IB Gateway or TWS for automation?

Use IB Gateway. It uses fewer resources, has no trading GUI to get in the way, and is what IBC and most Docker images target. Use TWS only if you also need its charts or manual trading on the same machine.


Conclusion


Getting IB Gateway into Docker takes an afternoon. Getting it to run for months with nobody watching takes all three layers: a maintained container, a session lifecycle you planned for, and an application that expects disconnects, reconciles after them, keeps exits at the broker and tells a human when something is wrong.



We build production trading systems on Interactive Brokers: signal engines, order and exit automation, multi-account allocation, alerting and kill switches. If your strategy works and you want it to run without someone watching the screen, book a call with our team.


imgi_48_Arpan Desai Profile Photo (1).png

About Author 

Arpan Desai

CEO & FinTech Expert

Arpan brings 14+ years of experience in technology consulting and fintech product strategy.
An ex-PwC technology consultant, he works closely with founders, product leaders, and API partners to shape scalable fintech solutions.

 

He is connected with 300+ fintech companies and API providers and is frequently involved in early-stage architectural decision-making.

Rectangle 6067.png

Contact Us

Are you looking to build a robust, scalable & secure Fintech solution?
bottom of page