Home > Net >  Error with linking containers in docker-compose
Error with linking containers in docker-compose

Time:05-24

I am trying to build an image and a container of a application with docker compose. However when i try to link the containers it keeps giving the error "Service api has a link to service 'containername' which is undefined". Does someone know what i am doing wrong?

This is my code:

version: "3.9"
services:
  db:
    image: mysql:5.6
    ports:
      - 23306:3306
    volumes:
      - .:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: quint
      MYSQL_DATABASE: cddb_quin
      MYSQL_USER: cddb_quint
      MYSQL_PASSWORD: quint
    container_name: cddb_mysql
  api:
    build: ./backend
    ports:
      - 28080:8080
    image: javaimage:latest
    links:
      - cddb_mysql:mysql
    container_name: cddb_backend
  web:
    build: ./frontend
    ports:
      - 20080:80
    image: angularimage:latest
    links:
      - cddb_backend
    container_name: cddb_frontend

CodePudding user response:

Compose links: are an obsolete feature. In even vaguely modern Compose – any Compose file with a top-level services: block – Compose will automatically create a Docker network for you and attach all of the services to it. You can almost always safely delete links: without losing any functionality.

The one thing that it's possible to do with links: but not Docker networking is to make another container visible under a different name. The links: [cddb_mysql:mysql] syntax you have does this. There's not particularly any benefit to doing this, though.

So the easiest way to fix the error you're getting is to just delete all of the links: blocks. You don't show how you're configuring your database connection, but you need to configure it to point to the Compose service name of the database db. Networking in Compose in the Docker documentation describes this setup further.

(You can also delete all of the container_name: settings, and on the images you build:, you can delete their manual image: names if you're not planning to push them to a registry.)

version: '3.8'
services:
  api:
    build: ./backend
    ports:
      - 28080:8080
    environment:
      - MYSQL_HOST=db
  db: { ... }
  backend: { ... }
  • Related