dockerlocalhostdocker-network

Acccess host localhost from inside a Docker container


So I have VPS that exposes an API endpoint on localhost at port 8080.

I have a Svelte app that must need the endpoint. To build the svelte app I'm using docker-compose.yaml with

version: '3.8'

services:
  frontend:
    build:
      context: ./frontend
      target: development
    volumes:
      - ./frontend:/app
      - /app/node_modules
    ports:
      - "5173:5173"
    environment:
      - NODE_ENV=development

and inside the frontend folder I have the Docker file

FROM node:23-alpine as development

WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .

EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host"]

FROM node:23-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx:alpine as production
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

With this setup, the Svelteapp seems unable to access the local host on the host machine. The only way I was able to access it was to add the line network_mode: host to the docker-compose. yaml. In this way, I was able to access the localhost IP of the host directly with 192.168.1.17, which is the IP on my whole local network.

Is there a way to access the localhost host IP directly using localhost keyword from the container or just no hard-coding the IP which could change


Solution

  • There's no way, except network_mode: host, to reach the host using the localhost name. That's because when a container is on a Docker network (the default behavior), the container has it's own IP address and localhost means the container itself.

    On a Docker bridge network, the main gateway is the host. You can add a name for it using extra_hosts and the special name host-gateway. It's common practice to use the hostname host.docker.internal as the name you use.

    So change your docker-compose.yml file to

    version: '3.8'
    
    services:
      frontend:
        build:
          context: ./frontend
          target: development
        volumes:
          - ./frontend:/app
          - /app/node_modules
        ports:
          - "5173:5173"
        extra_hosts:
          - host.docker.internal:host-gateway
        environment:
          - NODE_ENV=development
    

    Now you can access the host from inside the container by using the hostname host.docker.internal.