Skip to content

Ports and Environment Variables

By default a container is fully isolated — its ports are not reachable from the host. The -p flag publishes a port, creating a mapping between a host port and a container port:

Terminal window
docker run -d -p 8080:80 nginx:alpine

The format is -p <host-port>:<container-port>. After this command, opening http://localhost:8080 in your browser reaches port 80 inside the container.

You can publish multiple ports:

Terminal window
docker run -d -p 8080:80 -p 8443:443 nginx:alpine
Terminal window
# Only accessible from localhost, not the network
docker run -d -p 127.0.0.1:8080:80 nginx:alpine

Containers read configuration from environment variables. Pass them with -e:

Terminal window
docker run -d \
-e MYSQL_ROOT_PASSWORD=secret \
-e MYSQL_DATABASE=myapp \
mysql:8

Each -e sets one variable inside the container.

For more than a few variables, keep them in a file and use --env-file:

.env
MYSQL_ROOT_PASSWORD=secret
MYSQL_DATABASE=myapp
MYSQL_USER=app
MYSQL_PASSWORD=apppass
Terminal window
docker run -d --env-file .env mysql:8

This keeps secrets out of your shell history.

Giving a container a predictable name makes every subsequent command easier:

Terminal window
docker run -d \
--name mysite \
-p 8080:80 \
nginx:alpine

Now you can use mysite instead of a random ID in every docker stop, docker logs, and docker exec command.

Terminal window
docker run -d \
--name webserver \
-p 8080:80 \
-e NGINX_HOST=localhost \
nginx:alpine
# Verify
docker ps
curl http://localhost:8080
# Run nginx with a port mapping and an env var
docker run -d \
  --name webserver \
  -p 8080:80 \
  -e NGINX_HOST=localhost \
  nginx:alpine

# Confirm the mapping
docker ps

# Fetch the default page (should return HTML)
curl -s http://localhost:8080 | head -5

# Inspect the env var inside the container
docker exec webserver env | grep NGINX

# Clean up
docker stop webserver && docker rm webserver
What does '-p 3000:8080' mean?
Which flag passes a file of KEY=VALUE pairs as environment variables?
If you run a container WITHOUT -p, can you reach its port from the host?
What is the benefit of using --name when running a container?