We can now have a service be connected to a defined network using the networks key: Here we’ll define two networks: frontend and backend. In that case, we’ll need to put these services on separate networks by defining them using the network key. This works really well on its own, but lets say we don’t want web to know anything about api-internal or db. AppSettings:APIBaseURL= Custom Networks AppSettings:DBConnectionString=postgres://db:5432 Put it all together for the other services, and it looks something like this: AppSettings:APIBaseURL= Inside the container, the APIBaseURL will look like But from the host machine, the url will resolve to Now we can have full communication between containers. It will match an AppSettings variable defined in the web’s appsettings.json under AppSettings:APIBaseUrl. We’d like web to get the IP of api-external, so we’ll pass an environment variable using Docker’s environment key. To show that, let’s make some changes to the docker-compose.yml file. Each container (api-external, api-internal, db, and web) joins the myapp_default network and can now look up the hostnames of the others. When we run this compose file, a default network called myapp_default is created. The web project requires the use of the external API, whereas the internal API relies on the database. In this example, I’ve set up a web project with two APIs (internal and external) and a Postgres database. In the root of your project, add a docker-compose.yml file that looks similar to this:ĭockerfile. You should already have your individual projects set up with Docker files.
In a couple of short steps, I’ll show you how to quickly get a custom network running in your application and inject container references into your project’s environment for quick setup. Fortunately, Docker Compose solves this networking problem by making it easy for your containers to communicate without knowing one another’s context. If you have a containerized application composed of multiple services, it can become a burden to string together in-network communication.