-1

I am creating a container for my node application. I have exposed the port 8888 from the container. So, when i run the docker using:

docker run imageName

then, browse, http://localhost:8888/. It doesn't work.

But, if run:

docker run -p 8888:8888 imageName. It works. So this maps, localhost's port to docker container port. But, Is there a way to map these ports other than docker runs' -p flag

DockerFile

FROM node:alpine

WORKDIR /app

COPY . .

RUN npm install

# Expose a port.
EXPOSE 8888

# Run the node server.
ENTRYPOINT ["npm", "start"]
Waseem
  • 69
  • 11
  • Using the `-p` flag is the only way to map your container's port to the host machine when starting it with `docker run`. You can, however, map ports using docker-compose (in a yml file) without a command-line argument/flag, if that's what you're after. See [this answer](https://stackoverflow.com/questions/22111060/what-is-the-difference-between-expose-and-publish-in-docker) for a bit more about what `EXPOSE` in a Dockerfile really does. – Ryan Mar 18 '21 at 06:28
  • you can also have a look at the `-P` (p in capitals) that expose all ports defined in the dockerfile without requiring the values manually. – Krishna Chaurasia Mar 18 '21 at 06:37
  • `-P` should be used only on debugging or development environment, it is always unsafe otherwise. – Niklas Mar 18 '21 at 07:18
  • `-P` maps to random host ports, so it's not too useful even in debug and testing. In many years of working intensively with docker I am yet to find a good use for `-P` – Software Engineer Mar 18 '21 at 08:21
  • @Ryan -- the answer you have linked to is simply wrong (despite hundreds of up-votes). That question does have a correct answer though: https://stackoverflow.com/a/47594352/2051454 – Software Engineer Mar 18 '21 at 08:25
  • (That answer was essentially correct before there were Docker networks.) – David Maze Mar 18 '21 at 10:53

1 Answers1

1

Short answer: No

Long answer: Not exactly

Docker CLI

Using the docker cli? Then the only way to expose ports is to use the -p or -P. The difference is that '-P' maps all ports declared with EXPOSE in the Dockerfile to a random port on the host.

Docker Compose

Docker compose is the declarative form of the docker cli. It can expose ports using a -ports list as part of a service object (in yaml).

version: "3.9"
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"

Kubernetes

Another way to expose container ports is to use kubernetes. There are many ways to achieve this, the most simple being a node-port definition as part of a service:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: MyApp
  ports:
    - port: 80
      targetPort: 80
      nodePort: 30007
Software Engineer
  • 15,457
  • 7
  • 74
  • 102