Docker + Airflow – Unable to connect to MySQL on host from docker container

I’m using dockerized Airflow based on ‘puckel/docker-airflow:1.10.9’ image.

docker-compose file is the following:

version: '3.5'

services:
  postgres:
    image: postgres:12.3-alpine
    environment:
      POSTGRES_DB: airflow
      POSTGRES_USER: airflow
      POSTGRES_PASSWORD: airflow
    ports:
      - 5432:5432
    volumes:
      - ./data/postgres:/var/lib/postgresql/data

  webserver:
    build:
      context: .
      dockerfile: docker/development/webserver/Dockerfile
    restart: always
    depends_on:
      - postgres
    environment:
      ...
    volumes:
      ...
    ports:
      - 8080:8080
    command: webserver
    healthcheck:
      test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
      interval: 30s
      timeout: 30s
      retries: 3

Connection to MySQL on host is required in one of the tasks in DAG.

Connection details are the following:
enter image description here

When I’m trying to trigger DAG, the task instance fails with _mysql_exceptions.OperationalError: (2006, "Unknown MySQL server host 'host.docker.internal' (-2)")

I’ve tried the same as in this issue, but the problem still persists.

Also, here are some failed docker network checks:

$ docker run --rm webserver ping 'host.docker.internal'

ping: bad address 'host.docker.internal'

and

$ docker run --rm alpine nslookup host.docker.internal

Unable to find image 'alpine:latest' locally
latest: Pulling from library/alpine
df20fa9351a1: Pull complete 
Digest: sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321
Status: Downloaded newer image for alpine:latest
Server:         192.168.100.1
Address:        192.168.100.1:53

** server can't find host.docker.internal: NXDOMAIN

** server can't find host.docker.internal: NXDOMAIN


UPDATE:
I’ve added HOST_IP and HOST_DOMAIN to /etc/hosts inside webserver container:

HOST_DOMAIN="host.docker.internal"
if ! ping -q -c1 $HOST_DOMAIN > /dev/null 2>&1
then
  HOST_IP=$(ip route | awk 'NR==1 {print $3}')
  # shellcheck disable=SC2039
  echo "$HOST_IP   $HOST_DOMAIN" >> /etc/hosts
fi

and now I can ping ‘host.docker.internal’ from inside webserver container:

# [email protected]:/usr/local/airflow# ping host.docker.internal

PING host.docker.internal (192.168.240.1): 56 data bytes
64 bytes from 192.168.240.1: icmp_seq=0 ttl=64 time=0.042 ms
64 bytes from 192.168.240.1: icmp_seq=1 ttl=64 time=0.034 ms
64 bytes from 192.168.240.1: icmp_seq=2 ttl=64 time=0.060 ms
64 bytes from 192.168.240.1: icmp_seq=3 ttl=64 time=0.052 ms
64 bytes from 192.168.240.1: icmp_seq=4 ttl=64 time=0.055 ms
64 bytes from 192.168.240.1: icmp_seq=5 ttl=64 time=0.050 ms
64 bytes from 192.168.240.1: icmp_seq=6 ttl=64 time=0.045 ms

But problem persists…

Source: StackOverflow