In the last lesson Create a Custom Image with a Dockerfile running Node.js, our backend stopped working again because it couldn’t find the database.
One of the advantages of running containers is that they run in isolation. As far as the container is concerned, nothing exists outside of it. It behaves as if it was its own operating system. This is why the backend can’t find the database on "localhost". The two containers are running on the same host but as far as the backend is concerned, there is no database. The same goes for the database. It can’t see anything outside of what is running in its container therefore it can’t see the backend application running.
When you need a way for multiple containers to talk to each other, Docker has a tool called networks to help you. We'll use a network to allow our backend to successfully connect to the database.
Joel Lord: [0:01] First, start by creating the case course network. Then start your database with the additional --network parameter. Finally, start your backend with the same --network parameter.
[0:32] If you try to reach the /healthroute, you're still getting an error message saying that the backend can't connect to the database server. That's because the API tried to connect to a database on localhost. It actually now runs in a container called k8s-course-db.
[0:51] Remember how we added an environment variable for a database server? This is where it will come in handy. You can restart your backend by adding in the -e parameter to pass in the name of the database server. Note that this container was running in detached mode. If you want to verify that your containers are indeed running, you can use docker ps.
[1:15] If you want to see if there are any error messages in your backend service, you can view the logs with the logs command followed by the name of the container. If everything worked, you should see a message saying that the server is running.
[1:31] Now that you have a working database and backend, it's time to go back to our frontend and build another container to serve those files.