Michael Allen
Michael Allen

Reputation: 5828

Prevent publishing ports defined in compose file

I have a docker compose file that defines a service that will run my application and a service that that application is dependent on to run:

services:
  frontend:
    build:
      context: .
    volumes:
      - "../.:/opt/app"
    ports:
      - "8080:8080"
    links:
      - redis
    image: node
    command: ['yarn', 'start']
  redis:
    image: redis
    expose:
      - "6379"

For development this compose file exposes 8080 so that I can access the running code from a browser.

In jenkins however I can't expose that port as then two jobs running simultaneously would conflict trying to bind to the same port on jenkins.

Is there a way to prevent docker-compose from binding service ports? Like an inverse of the --service-ports flag?


For context:

In jenkins I run tests using docker-compose run frontend yarn test which won't map ports and so isn't a problem.

The issue presents when I try to run end to end browser tests against the application. I use a container to run CodeceptJS tests against a running instance of the app. In that case I need the frontend to start before I run the tests, as they will fail if the app is not up.

Upvotes: 3

Views: 2180

Answers (2)

Ali Hallaji
Ali Hallaji

Reputation: 4392

For preventing to publish ports outside the docker network you just need to write on a single port in the ports segment.

Instead of using this:

ports:
    - 8080:8080

Just use this one(at below):

ports:
    - 8080

Upvotes: 0

Robert
Robert

Reputation: 36733

Q. Is there a way to prevent docker-compose from binding service ports?

It has no sense to prevent something that you are asking to do. docker-compose will start stuff as the docker-compose.yml file indicates.

I propose duplicate the frontend service using extends::

version: "2"
services:
  frontend-base:
    build:
      context: .
    volumes:
      - "../.:/opt/app"
    image: node
    command: ['yarn', 'start']

  frontend:
    extends: frontend-base
    links:
      - redis
    ports:
      - "8080:8080"

  frontend-test:
    extends: frontend-base
    links:
      - redis
    command: ['yarn', 'test']

  redis:
    image: redis
    expose:
      - "6379"

So use it as this:

docker-compose run frontend         # in dev environment
docker-compose run frontend-test    # in jenkins

Note that extends: is not available in version: "3", but they will bring it back again in the future.

Upvotes: 1

Related Questions