Ports and Environment Variables
Publishing ports with -p
Section titled “Publishing ports with -p”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:
docker run -d -p 8080:80 nginx:alpineThe 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:
docker run -d -p 8080:80 -p 8443:443 nginx:alpineBind to a specific host IP
Section titled “Bind to a specific host IP”# Only accessible from localhost, not the networkdocker run -d -p 127.0.0.1:8080:80 nginx:alpinePassing environment variables with -e
Section titled “Passing environment variables with -e”Containers read configuration from environment variables. Pass them with -e:
docker run -d \ -e MYSQL_ROOT_PASSWORD=secret \ -e MYSQL_DATABASE=myapp \ mysql:8Each -e sets one variable inside the container.
Using an env file
Section titled “Using an env file”For more than a few variables, keep them in a file and use --env-file:
MYSQL_ROOT_PASSWORD=secretMYSQL_DATABASE=myappMYSQL_USER=appMYSQL_PASSWORD=apppassdocker run -d --env-file .env mysql:8This keeps secrets out of your shell history.
Naming containers with --name
Section titled “Naming containers with --name”Giving a container a predictable name makes every subsequent command easier:
docker run -d \ --name mysite \ -p 8080:80 \ nginx:alpineNow you can use mysite instead of a random ID in every docker stop, docker logs, and docker exec command.
Putting it together
Section titled “Putting it together”docker run -d \ --name webserver \ -p 8080:80 \ -e NGINX_HOST=localhost \ nginx:alpine
# Verifydocker pscurl 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