Search code examples
apachedockerdocker-composedockerfileappdomain

Accessing docker containerized application using custom domain name


I'm trying to set up a custom domain name locally for my app which runs on docker, so instead of accessiing my app from the browser with http://localhost:8080 to use something like http://myapp.dev

This is my /etc/hosts file

127.0.0.1       localhost
127.0.0.1       myapp.dev

In my Dockerfile I'm having this vhost file COPY docker/vhost.conf /etc/apache2/sites-available/000-default.conf that copies the config from local into the apache configuration

<VirtualHost *:80>

    ServerName myapp.dev
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public

    ErrorLog /var/log/apache2/error.log
    CustomLog /var/log/apache2/access.log combined

</VirtualHost>

But when I try to access the app with the local domain name getting a message saying Unable to connect from the browser.

Am I doing something wrong?


Solution

  • Copying vhost.conf into docker image will impact the apache server port inside the container. Not how it is accessed from the physical machine.

    vhost.conf should not bound with the hostname ServerName myapp.dev because inside the container the hostname will be different.

    Change ServerName to accept requests from 127.0.0.1 or *

    Host to container port mapping should be done to access the application from the browser

    docker run --name <container-name> -p 80:80 -d <image-name>
    

    This command will bind the host port to the container port. (In this case, the webserver is running on port 80 and configured to bind with the host port 80)

    For more info -



    In docker-compose file, it is used as follows - https://docs.docker.com/compose/networking/

    version: "3"
    services:
    
      apache:
        image: apache:latest
        ports:
          - "80:80"
    

    Example, Not using docker-compose. But once the container is in running state, port binding can be verified as described.

    Verify if port binding is successful using the output of docker container ls

    $ docker run --name mynginx1 -p 80:80 -d nginx
    ba2565a8e7e4a3e5909cb055603eb5161dd50e6f17019b2a9f11ba9b2b4888e4
    $ docker container ls | grep mynginx1
    ba2565a8e7e4        nginx               "nginx -g 'daemon of…"   12 seconds ago      Up 10 seconds       0.0.0.0:80->80/tcp    mynginx1
    

    Next, Update the /etc/hosts file with the required DNS name.