Search code examples
phpdockerubuntudocker-composelampp

How to make two virtual host point and same project while using docker compose to serve?


I have two domains sharing same codebase and database. Now I need two domains to connect to two different database respective to domain. I am using docker compose to serve in my local setup. Then i go to my browser and enter localhost:2000 to see my project served. I need two different domain say xyz.com and xyz.net to point to same project. Can anyone help me on this?


Solution

    1. you need to resolve that both your domains when accessed point to localhost. In /etc/hosts add:
    127.0.0.1 xyz.com
    127.0.0.1 xyz.net
    

    Now if you access xyz.com or xyz.com in your browser it will resolve to your local machine.

    1. Configure apache vhosts to point to localhost:2000, something like this:
    <VirtualHost *:80>
            ServerName xyz.com
            ProxyPreserveHost On
            ProxyRequests off
    
            <Location />
                    ProxyPass http://localhost:2000/
                    ProxyPassReverse http://localhost:2000/
                    Order allow,deny
                    Allow from all
            </Location>
    </VirtualHost>
    

    And second one:

    <VirtualHost *:80>
            ServerName xyz.net
            ProxyPreserveHost On
            ProxyRequests off
    
            <Location />
                    ProxyPass http://localhost:2000/
                    ProxyPassReverse http://localhost:2000/
                    Order allow,deny
                    Allow from all
            </Location>
    </VirtualHost>
    

    Enable both virtual hosts (sudo a2ensite [name].conf) and reload apache. You will also need proxy_http mod: sudo a2enmod proxy_http. Now both url point to your localhost:2000.

    1. In your PHP app detect domain and based on that connect to whatever db you need. I used this file g.php:
    <?php
    
    var_dump($_SERVER['HTTP_HOST']);
    

    and served it with development server in php on localhost:2000 (you will have it on docker):

    php -S localhost:2000 g.php 
    PHP 7.0.33-0ubuntu0.16.04.15 Development Server started at Thu Jul  9 20:34:03 2020
    Listening on http://localhost:2000
    

    When I access xyz.net in browser i get: string(7) "xyz.net" When I access xyz.com in browser i get: string(7) "xyz.com"