basagabi
basagabi

Reputation: 5064

Docker use different hostname per container

I am using Docker for Windows and would like to know if each container could have its own IP address that I could map on the host file and assign a hostname.

Currently, when I input http://localhost:8081/ on my browser, it is showing my Laravel application (which is fine) However, rather than having that URL, I wanted it to be something like: http://myapp.local/ to give it a more distinctive name.

Since I will be running multiple containers, most likely I will run it using multiple ports like so:

http://localhost:8082/

http://localhost:8083/

and so on..

Which should map in such way:

http://localhost:8082 = http://anotherapp.local

http://localhost:8083 = http://andanotherapp.local

Here's my docker-compose.yml

version: '3.7'
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    image: 'laravelapp'
    ports:
      - 8081:80
    volumes:
      - ./:/var/www/html
    container_name: laravelapp
  db:
    image: mysql:5.7
    restart: always
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: 'laraapp_db'
      MYSQL_USER: "homestead"
      MYSQL_PASSWORD: "secret"
      MYSQL_DATABASE: "laravelapp_db"
      MYSQL_ROOT_PASSWORD: "secret"
    volumes:
      - ./.database:/var/lib/mysql
    container_name: laraveldb

Upvotes: 2

Views: 1008

Answers (1)

anemyte
anemyte

Reputation: 20296

You can rework localhost to something.local but this does not include application port. There are multiple ways you can solve this (reverse-proxy, extracting Docker DNS, to name a few) but the closest to your question will be changing port forwarding rules to include listen address. Here is an example for your snippet:

services:
  app:
    ports:
      - 127.0.10.10:80:80

Then you add a rule to your hosts file:

127.0.10.10 something.local

Your initial port configuration (- 8081:80) was like forward any packet received by host's port 8081 to container's 80. 127.0.10.10:80:80 means forward any packet received by host's port 80 on 127.0.10.10 IP-address to container's port 80.

Now you can assign different loopback IP-addresses to each of your services and add an according rule to the hosts file. Note that since these are loopback IPs, you will not be able to reach them from any other machine on the network. I guess that's fine for dev environment, if it's not - you need a reverse-proxy.

Upvotes: 2

Related Questions