Docker - Networking - Run a Container with a Specific Network

By default, containers are connected to the bridge network, but you can choose which network to use when starting a container.

Here is an example of running a container using the default bridge network:

docker run --name my_nginx --network bridge -p 8080:80 -d nginx

NOTE:

  • –name my_nginx - This names the container as my_nginx.
    • Containers are normally given random names, but specifying the –name option assigns a user-defined name to the container, making it easier to manage later.
  • –network bridge - This specifies that the container should be connected to the bridge network, which is the default Docker network type for container-to-container communication on a standalone host.
  • -d - This flag runs the container in detached mode, meaning it runs in the background.
    • This will not show the logs or the terminal of the container unless you explicitly connect to it or check its logs later.
  • -p 8080:80 - Maps port 8080 on the host to port 80 on the container (where Nginx is listening).

The Nginx container is accessible via localhost:8080.

NOTE: If the Nginx image is not already present on the local system, Docker will first check the Docker Hub to pull the nginx image.


Try to send requests to the container

curl http://localhost:8080

NOTE: This should show a default HTML web page that nginx uses.