'Can't figure out what ports to use in docker compose [ECONNREFUSED, port alredy used...]

version: '3.3'

services:
  mysqldb:
    image: mysql:8
    restart: on-failure
    env_file: ./.env
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=database
    ports:
      - 3307:3306
    volumes:
      - db:/var/lib/mysql
    network_mode: "host"
  app:
    depends_on:
      - mysqldb
    build: ./
    restart: on-failure
    env_file: ./.env
    ports:
      - 8004:8003
    environment:
      - DB_HOST=mysqldb
      - DB_USER=user
      - DB_PASSWORD=password
      - DB_NAME=database
      - DB_PORT=3306
    stdin_open: true
    tty: true
volumes: 
  db:

I want to properly configure the ports in my docker compose, but I am not sure exactly how to go about it. Up until this point I was following a medium tutorial on how to set up docker with node.js and mysql but I am getting ECONNREFUSED for 127.0.0.7:3306(mysql port) and a message that the 8003 port is already taken(I have tried killing processes, restarting... but the issue seems to be in docker compose). If I run mysql service and npm start, or just the dockerfile, it works fine with the database but doesn't in docker.

My mysql port here is 3306 and my nodejs app is running on 8003. I have also tried to set it to 3306:3306 and 8003:8003 but haven't had any luck.

I'm adding this just in case it's usefull somehow:

FROM node:latest

WORKDIR /home/user/...
COPY package*.json ./

RUN npm install
RUN npm ci --only=production

COPY . .
EXPOSE 8003
CMD [ "npm", "start" ]

How did I missconfiger the ports?



Solution 1:[1]

You might have old containers around that used the ports and exited. They don't release the ports until you remove them.

To see if you have one that uses port 3306, you can run

docker ps -a | grep :3306

If there is a container with status 'Exited', you can remove it with

docker rm <container name>

Then the port should be available again

A quick way to remove all exited containers is (on Linux)

docker rm $(docker ps -aq)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hans Kilian