'Issues with Docker networking on a GCP instance

I'm trying to build and run a simple Docker container (using docker-compose to do this) on a GCP Instance (Ubuntu 20.04), and it seems that the container cannot access the internet, unless I run it using

docker run --net=host [...]

or use in my docker-compose.yml something like:

service:
  build:
    ...
    network: host
  network_mode: host
  ...

I'm wondering why it is so, that a simple docker container on a standard GCP instance with Ubuntu 20.04 should require some specific configuration to access Internet, and why I see almost no mention of this while searching for this issue on the web.

Am I doing something wrong, is there a better way to do this?



Solution 1:[1]

See Container networking for Docker and the principle is applied consistently across other container runtimes too.

Using --net=host or network_mode: host binds container(s) to the host's network.

Rather than broadly publishing all of a container's or service's ports to the host network (and thus making them host public), you can be more precise using --publish=[HOST-PORT]:[CONTAINER-PORT] or ports to expose container ports as host ports (and potentially remap these too).

One (of several advantages) to the not-published-by-default behavior is that you must take a second step to publish a container's ports to a host where there is increased possibility that the service may be accessed (via its ports) by undesired actors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1