Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #37: What Do Links Do in Docker Compose?

blog/cards/docker-tips-and-tricks.jpg

Docker is a few years old now, and if you're dealing with older Docker projects, you may run into links. Here's what it is.

You may see this out in the wild if you take on legacy or older Dockerized apps.

Here’s what a legacy v1 Docker Compose file might look like:
redis:
  expose:
    - "6379"

webapp:
  links:
    - "redis"

In the above example, redis is exposing port 6379. This won’t publish it back to the Docker host, but it will make it available to any containers who happen to link redis (such as the webapp container in this example).

Back in the day Docker didn’t have networking, so the links property along with expose is how you let 2 containers communicate. This also ensured that redis would get started if you started webapp directly because links also doubled as a way to start dependent containers.

Then if you wanted to publish the port on the Docker host, you could still use ports.

Here’s the updated v2 version of the above:
version: "2"

services:
  redis:
    expose:
      - "6379"

  webapp:
    depends_on:
      - "redis

In the above example, we no longer need to use links because Docker Compose will automatically create a network for our Compose project and containers on that network will be able to talk freely with each other.

We also added in a depends_on property which will ensure redis gets started if it’s not already running if we directly start webapp.

Technically we don’t even need to add expose because the official Redis Docker image has EXPOSE 6379 in its Dockerfile. I just added it here to be explicit in the example.

Like usual, if you wanted to publish the port on the Docker host you could use ports too.

Moving forward you should use networks and depends_on and avoid using links all together because it is considered legacy and may be deprecated. You can continue using expose and ports nowadays and both are considered standard to use.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.


Comments