Dockerfile Expose Example !!hot!! Review
COPY nginx.conf /etc/nginx/nginx.conf # Image EXPOSEs 3000, but we can run on different port internally docker run -p 8080:8080 -e PORT=8080 myapp Corresponding Dockerfile FROM node:18 ENV PORT=3000 # Default EXPOSE $PORT CMD ["sh", "-c", "npm start -- --port $PORT"] 10. Key Takeaways | Feature | Behavior | |---------|----------| | EXPOSE | Documentation only, no port publishing | | -p flag | Publishes port to specific host port | | -P flag | Publishes all EXPOSED ports to random ports | | Multiple ports | Can specify multiple EXPOSE lines | | TCP/UDP | Default TCP, specify /udp for UDP | | Port ranges | Supported by some runtimes (9000-9010) | Real-World Production Example FROM node:18-alpine AS frontend WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . EXPOSE 3000 8080 USER node Security: non-root user, specific port range CMD ["node", "server.js"]
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
CMD ["npm", "start"] FROM python:3.11-slim WORKDIR /app dockerfile expose example
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 CMD curl -f http://localhost:8000/health || exit 1
COPY . . EXPOSE 8000/tcp # Main web application EXPOSE 8080/tcp # Admin interface EXPOSE 5432/tcp # Internal database (documentation only) UDP port example EXPOSE 53/udp # DNS service Port range (if supported by your container runtime) EXPOSE 9000-9010/tcp COPY nginx
CMD ["/myapp"] # View exposed ports from image docker image inspect myapp --format='json .Config.ExposedPorts' View actual published ports docker ps --format "table .Names\t.Ports" Detailed port mapping docker port mycontainer 7. Security & Best Practices # ✅ GOOD: Minimal exposure FROM node:18-alpine EXPOSE 3000 # Only what's necessary ❌ BAD: Over-exposing FROM node:18-alpine EXPOSE 1-65535 # Don't do this ✅ GOOD: Use environment variables FROM python:3.11 ENV APP_PORT=8000 EXPOSE $APP_PORT # Variable expansion works! ✅ GOOD: Document protocol EXPOSE 8000/tcp EXPOSE 53/udp 8. Advanced: HEALTHCHECK Integration FROM nginx:alpine EXPOSE 80 443 Health check using exposed ports HEALTHCHECK --interval=30s --timeout=3s CMD curl --fail http://localhost:80 || exit 1
COPY package*.json ./ RUN npm install
: EXPOSE is metadata. Always use -p or -P when running containers to actually access the ports!