Streamline Local Development on macOS: Custom Domain Names for Docker and Services
Setting up a local domain name on OSX can streamline your development process by allowing you to access your Docker containers or other services via a custom, easy-to-remember URL. This is particularly useful for multisite applications, as it lets you choose a custom domain for every site for local development. It's also possible to add several custom domain names for 127.0.0.1.
Step 1: Open Your Terminal
Launch the Terminal application from your Applications folder or use Spotlight Search.
Step 2: Edit the Hosts File
Open the Hosts File: Use the following command to open the hosts file in a text editor. This file maps domain names to IP addresses.
sudo vim /etc/hosts
The
sudo
command is necessary because the hosts file is a system file, and editing it requires administrative privileges. You'll be prompted to enter your password.Add Your Custom Domain: Add new lines in the hosts file with the desired local domain names and the IP address of your service. For instance, to map
myapp.local
andmysite.local
to127.0.0.1
:127.0.0.1 myapp.local 127.0.0.1 mysite.local
In vim, press
i
to enter insert mode, add the lines, then pressEsc
to exit insert mode. Type:wq
and pressEnter
to save and exit.Adding these entries tells your computer to resolve
myapp.local
andmysite.local
to127.0.0.1
, which is the loopback address pointing to your local machine. This is useful for accessing locally hosted services or Docker containers via a custom URL.
Step 3: Save and Exit
Save Changes: In vim, after adding your custom domain entries, press
Esc
to exit insert mode. Then type:wq
and pressEnter
to save and close the file.Flush DNS Cache: Ensure your changes take effect by flushing the DNS cache. This clears any cached DNS records and forces the system to read the updated hosts file.
sudo dscacheutil -flushcache
Flushing the DNS cache is crucial to ensure that your changes to the hosts file are recognized by your system immediately.
Step 4: Configure Docker Container (if using Docker)
Run Your Docker Container: Make sure your Docker container is running. For example, to run an NGINX server, use the following command:
docker run -it --rm -d -p 80:80 --name my-nginx nginx
This command starts an NGINX container, mapping port 80 of the container to port 80 of your local machine. The
--rm
flag ensures the container is removed after it stops, and-d
runs the container in detached mode.Access via Custom Domain: You should now be able to access your Docker container using the custom domain names, e.g.,
http://myapp.local
andhttp://mysite.local
. Open a web browser and navigate to these URLs to verify that your container is accessible via the custom domains.
Happy coding!