Docker volume mounting and port mapping¶
Docker volume mounting and port mapping are two fundamental mechanisms for configuring container runtime behavior, specifically regarding data persistence and network accessibility.^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md]
Volume Mounting¶
Volume mounting allows a user to connect a specific directory or file from the host machine to a path inside the container.^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md]
This is primarily used for data persistence. Because containers are ephemeral, any data written inside a container's filesystem is lost when the container is removed. By mounting a volume, changes are written to the host machine, ensuring data is not lost if the container stops or is deleted^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md]. Additionally, this technique is often used to inject configuration files into a container at runtime^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md].
Usage¶
The syntax requires the -v (or --volume) flag followed by the host path and the container path separated by a colon^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md].
Syntax: -v <host_directory>:<container_directory>
Example:
To mount a local directory named html to the Nginx html directory:
docker run -v /root/html:/usr/share/nginx/html ...
/root/html on the host will be visible inside the container at /usr/share/nginx/html^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md].
Port Mapping¶
Port mapping creates a tunnel between a port on the host machine and a port inside the container^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md]. This allows services running inside the container, which are isolated from the network by default, to be accessed via the host's IP address.
Usage¶
The operation uses the -p (publish) flag.^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md]
Syntax: -p <host_port>:<container_port>
Example: To access a web server running on port 80 inside the container via port 81 on the host:
docker run -p 81:80 ...
localhost:81 on the host machine forwards the traffic to port 80 within the container^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md].
Related Concepts¶
- [[Docker]]
- Dockerfile
Sources¶
^[400-devops__06-Kubernetes__k8s-paas__01.Docker(已熟悉的可以从第二章开始).md]