Deploy Nginx in Docker and mount the configuration file

Create local directory

First, create a directory on the host to store the Nginx configuration file. For example, create a nginxdirectory named to store Nginx configuration files.

mkdir nginx
mkdir nginx/nginx.conf
mkdir nginx/html

Pull Nginx image

Use the following command to pull the latest image of Nginx from Docker Hub:

docker pull nginx

Start Nginx container

Use the following command to start an Nginx container named nginx and nginxmount the host's directory to the directory inside the container /etc/nginx/conf.d:

docker run --name nginx -p 80:80 -p 443:443 -v /root/nginx/nginx.conf:/etc/nginx/nginx.conf -v /root/nginx/html:/usr/share/nginx/html -d nginx

Among them, --namespecify the container name, mount -v /path/to/nginx:/etc/nginx/conf.dthe host's nginxdirectory to the directory in the container /etc/nginx/conf.d, and -p 80:80map the container's port 80 to the host's port 80, -dwhich means starting the container in background mode.

Modify Nginx configuration file

nginx/nginx.confCreate a file named in the directory of the host default.confto modify the configuration of Nginx. For example, here is a simple configuration file example:

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

In this example, we specify Nginx's listening port, server name, and root directory.

Create new html file

nginx/dataCreate a file named in the host's directory index.html.

<!DOCTYPE html>
<html>
<head>
  <title>My Web Page</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <h1>Welcome to my web page!</h1>
  <p>This is a paragraph of text.</p>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
  <img src="image.jpg" alt="An image">
</body>
</html>

Restart Nginx container

nginxAfter modifying the file in the host directory default.conf, you need to restart the Nginx container for the configuration to take effect. Restart the container using the following command:

docker restart nginx

Visit Nginx

Access Nginx using the following command:

curl http://localhost

If everything goes well, you should be returned to the Nginx welcome page.

The above are the steps to deploy Nginx in Docker and mount the configuration file. It should be noted that the Nginx configuration file can be customized according to actual needs. You can refer to the Nginx official documentation for configuration.

Guess you like

Origin blog.csdn.net/njpkhuan/article/details/131280895