Euphe
Euphe

Reputation: 3699

Docker access localhost port from container

I have a container running a Nuxt.js (Vue.js) app, defined by docker_composes.yml:

version: '3'
services:
  vue:
    build: .
    image: registry.gitlab.com/something/app:${TAG}
    environment:
      - apiPath="http://localhost:5000/"
      - filePath="http://localhost:3000/"
    ports:
     - "${EXPOSED_PORT:-80}:${NUXT_PORT:-3000}"
    restart: always

The app is a frontend. I am running the backend on localhost, on port 5000. When the containerized app tries to connect to http://localhost:5000/ it fails.

What are my options? I don't want to put the backend into the docker_composes.yml and connect them by link. If it's the only option though, I will.

Upvotes: 62

Views: 109580

Answers (4)

Dasun_96
Dasun_96

Reputation: 193

if you want to access the host's localhost you can use the IP address of your host. in Linux use ifconfig command to get your IP address. Eg: if your host IP is 192.168.1.7 you can use 192.168.1.7:5000

Upvotes: 12

dryniex
dryniex

Reputation: 3603

localhost in your docker-compose.yaml file refers to container.

In order to access your local machine use host.docker.internal instead of localhost.

Upvotes: 94

yamenk
yamenk

Reputation: 51768

One way in which containers can communicate with one another is when they are attached to a common network. They can refer to each other using the container name. Example frontend can reach backend using backend:5000 where backend is the name the backend container.

To acheive this, create a docker network using docker network create app-network. Attach the backend container to this network using docker container attach <backend-container> app-network. Finally, update the compose file to the following:

version: '3'
services:
  vue:
    build: .
    image: registry.gitlab.com/something/app:${TAG}
    environment:
      - apiPath="http://backend:5000/" # replace backend-container name
      - filePath="http://localhost:3000/"
    ports:
     - "${EXPOSED_PORT:-80}:${NUXT_PORT:-3000}"
    restart: always
    networks:
     - app-network

networks:    
  app-network:
    external: true

Upvotes: 5

Ben A
Ben A

Reputation: 182

You could try using

network_mode: "host"

https://docs.docker.com/compose/compose-file/#network_mode

If you're on Windows or Mac you should be able to use:

docker.for.win.localhost
or
docker.for.mac.localhost

Upvotes: 8

Related Questions