VMWare – Access Docker Container in Ubuntu with Nginx

dockerlinuxnginxUbuntuvirtual-machines

I am running Ubuntu 22.04.3 LTS in a virtual machine. I installed Nginx with port 80.

When accessing http://localhost:80, the normal website is displayed by Nginx.

I then installed docker and two images. I gave the image API access on port 9000.

But when accessing http://localhost:9000, an error is displayed. Accessing in postman returns a 404.

It seems I need to link or allow port 9000 in Nginx, or to link the access from docker to the port.

I was unable to find how to allow more ports in Nginx or how to link the container exposed in port 9000. This is how it shows for the image in docker:

0.0.0.0:9000->9000/tcp, :::9000->9000/tcp  

Performed the steps for server:

cd /etc/nginx/sites-enabled
sudo "${EDITOR:-vi}" docker
server {
       listen 80;
       listen [::]:80;

       server_name example.ubuntu.com;

       root /var/www/docker;
       index index.html;

       location / {
               try_files $uri $uri/ =404;
       }
}

If I run GET in postman: http://localhost:9000/kalum-management/v1/jornadas
it should return data.
For some reason, the confusion with Docker and Nginx got all mixed up and not sure how to expose the docker to port 9000.

Best Answer

Docker creates it own network and network adapter. When running the containers you can use the option network_mode host to be able to connect from the host operating system to the docker network where the container is linked to. I would recommend using docker compose and I will also show you a example docker-compose to publish more ports

version: '3'

    services:
      your_service_name:
        container_name: your_container_name
        image: your_image_name
        network_mode: host
        volumes:
          - /path/on/host:/mnt

Keep in mind that you can't use the public ports and network mode host together.

Save this file in a directory as docker-compose.yml and then run it with docker-compose up -d


Option 2

Or you figure out the ip address of the container using the following command

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_name_or_id>

And then instead of http://localhost:9000 you replace localhost with the ip of the container. It might not work because the docker network (automatically created when starting the container) is not reachable from the host (correct me if I'm wrong, but by default there is no routing between the main network of the host operating system and the docker network where the container is linked to)