1

I have mongodb running in the host machine (Ubuntu 23.04) in the default port. I have set the bind_ip to be 0.0.0.0. In my docker-compose file, I have added

extra_hosts:
      - "host.docker.internal:host-gateway"

And, I have my mongodb URI as mongodb://host.docker.internal/mydbname. However, I get Server selection timed out after 30000 ms

I tried to change network_type as host, after that it started working but why is this host.docker.internal working? Kindly please help.

Edit: This is the docker-compose.yml

version: "3.3"

services: web: image: test container_name: test restart: always build: context: . extra_hosts: - "host.docker.internal:host-gateway" ports: - "9345:5000" command: node app.js env_file: - backend/.env.production - frontend/.env.production

1 Answers1

2

podman pod

Docker compose is an old technology that allows packaging multiple containers into a unit. This has been largely replaced by podman pod, which provides everything that docker compose provides, except it also provides

  • SystemD unit generation -- make it run as service in systemd.
  • Kubernetes generation -- make it run on a cluster.
  • Rootless operation

It's also easier to use. To do what you're looking for you can do something like this. Note podman pod is just a shell command, no YAML needed (though there is a YAML method too).

#!/bin/sh

podman pod rm -f mongoapp;

podman pod create
--publish 27017
mongoapp;

podman run
--pod mongoapp
--detach
mongo:latest;

Now you have a pod created running mongo. Anything in the pod can reach it. This is where you'd run your "backend"

podman run -i    \
  --pod mongoapp \
  alpine:latest /bin/sh <<EOF
     apk update;
     apk add mongodb-tools;
     mongodump;
     exit;
EOF

Exposing Ports

Generally when you put Mongo in a container, you don't want anything to access it. You want the backend in a container communicating to it privately, and you want to provide access to the backend. To do this, we change podman pod create to publish the port,

#!/bin/sh

podman pod rm -f mongoapp;

podman pod create
--publish 27017
mongoapp;

podman run
--pod mongoapp
--detach
mongo:latest;

And now anything outside of it can access it as if it was running on the host (if your host has mongodump it should just work). You can even access it from containers outside the pod (since the port is published) by using host.containers.internal,

podman run -i    \
  --pod mongoapp \
  alpine:latest /bin/sh <<EOF
     apk update;
     apk add mongodb-tools;
     mongodump --host host.containers.internal;
     exit;
EOF
Evan Carroll
  • 2,921
  • 6
  • 37
  • 85