search
HomeOperation and MaintenanceNginxHow to scroll nginx log file in docker

Docker usage

1. docker ps to view running containers

2. docker images to view docker images

3. docker rm id (Container ID) Delete the container (the container ID can be viewed through docker ps, the container must be stopped before it can be deleted)

 3.1 Delete all containers docker rm `docker ps -a -q`

 4 . docker stop id (container id) stops the container from running

 5. docker rmi id (mirror id) deletes the image

 6. docker pull ubuntu:16.04 (mirror name: version number) downloads the image

 7. docker run -it ubuntu:16.04 Create and run the container container

 -t means to specify a pseudo terminal or terminal in the new container

 -i means to allow us Interact with (stdin) in the container

 -p specifies the mapped port

 -d Run the container in the background and print the container id

 7.1 docker run -dit ubuntu:16.04 Create and run the container in the background

 7.2 docker run -ditp 8080:8080 (host port: container port) ubuntu:16.04 Create and run the container in the background and map the port of the container

 8. docker attach id (Container id) Enter the running container environment

 9. Exit the container

 9.1 exit Directly exit the container and terminate the container running

 9.2 [ctrl p] [ctrl q ] (shortcut key) Exit the container, but will not terminate the container running

 10. docker commit -m'version identification' id (container id) ubuntu:16.04 (image and version number) Submit the image and generate the image ( You can use this command to package the built container into a new image or overwrite the original image (that is, modify the content of the original image, and the generated image name can be directly overwritten if the name of the generated image is the same as the version number))

How to scroll nginx log file in docker

Thoughts

nginx official actually gives instructions on how to rotate logs:

rotating log-files
in order to rotate log files, they need to be renamed first. after that usr1 signal should be sent to the master process. the master process will then re-open all currently open log files and assign them an unprivileged user under which the worker processes are running, as an owner. after successful re-opening, the master process closes all open files and sends the message to worker process to ask them to re-open files. worker processes also open new files and close old files right away. as a result, old files are almost immediately available for post processing, such as compression. Name
•Then send the usr1 signal to the nginx master process

•The nginx master process will do some processing after receiving the signal, and then ask the worker process to reopen the log file

•The worker process opens a new log file And close the old log file

In fact, the only work we really need to do is the first two points!


Create a test environment

Assuming that docker has been installed in your system, here we run an nginx container directly:

$ docker run -d \
 -p 80:80 \
 -v $(pwd)/logs/nginx:/var/log/nginx \
 --restart=always \
 --name=mynginx \
 nginx:1.11.3

Note that we bind the nginx log Mounted to the logs directory in the current directory.

Save the following content to the test.sh file:

#!/bin/bash
for ((i=1;i<=100000;i++))
do
 curl http://localhost > /dev/null
 sleep 1
done

Then run this script to simulate the generation of continuous log records.


Script to create rolling log

Create the rotatelog.sh file with the following content:

#!/bin/bash
getdatestring()
{
 tz=&#39;asia/chongqing&#39; date "+%y%m%d%h%m"
}
datestring=$(getdatestring)
mv /var/log/nginx/access.log /var/log/nginx/access.${datestring}.log
mv /var/log/nginx/error.log /var/log/nginx/error.${datestring}.log
kill -usr1 `cat /var/run/nginx.pid`

getdatestring function takes the current time and formats it as a string, such as "201807241310 ", the author prefers to name files with date and time. Note that the time zone is specified here through tz='asia/chongqing', because by default the format is UTC time, which is weird to use (you need to make up for 8 hours in real time). The following two mv commands are used to rename log files. Finally, send the usr1 signal to the nginx master process through the kill command.

Add executable permissions to the rotatelog.sh file through the following command and copy it to the $(pwd)/logs/nginx directory:

$ chmod +x rotatelog.sh
$ sudo cp rotatelog.sh $(pwd)/logs/nginx

Perform rolling operations regularly

Our nginx runs in a container, so we need to send the usr1 signal to the nginx master process in the container. Therefore we need to execute the rotatelog.sh script in the mynginx container through the docker exec command:

$ docker exec mynginx bash /var/log/nginx/rotatelog.sh

Executing the above command once will generate a batch of new log files as scheduled:

Next we configure this command in the scheduled task and let it be executed at 1 o'clock every morning once. Execute the crontab -e command and add the following lines at the end of the file:

* 1 * * * docker exec mynginx bash /var/log/nginx/rotatelog.shHow to scroll nginx log file in docker

Save and exit. The following picture is the effect of scrolling every 5 minutes during the author's test process:

How to scroll nginx log file in docker

Why not mv the log file directly in the host?

Theoretically, this is possible, because the contents of the data volume mounted through binding are the same when viewed from the host and from the container. But when you actually do this you are likely to run into permission issues. In the host machine, you generally use an ordinary user, while the owner of the log file generated in the container will be a special user, and generally other users will not be given write and execution permissions:


How to scroll nginx log file in docker

Of course, if you are using the root user on the host machine, there will be no problem.

Can the signal be sent from the host?

In fact, the full name of this question should be: Can a signal be sent from the host to the nginx master process in the docker container?

The answer is, yes.

We can use the command:

$ docker container kill mynginx -s usr

to process No. 1 in the container (nginx master )Send usr1 signal (this method can only send signals to process No. 1):

How to scroll nginx log file in docker

Combining the above two questions, we can write another way. Scroll nginx logs in docker. This method does not require executing commands in the container through the docker exec command, but completes all operations on the host:

•First rename the log file in the container data volume
• Send usr1 signal to process No. 1 in the container

The above is the detailed content of How to scroll nginx log file in docker. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
The Advantages of NGINX: Speed, Efficiency, and ControlThe Advantages of NGINX: Speed, Efficiency, and ControlMay 12, 2025 am 12:13 AM

The reason why NGINX is popular is its advantages in speed, efficiency and control. 1) Speed: Adopt asynchronous and non-blocking processing, supports high concurrent connections, and has strong static file service capabilities. 2) Efficiency: Low memory usage and powerful load balancing function. 3) Control: Through flexible configuration file management behavior, modular design facilitates expansion.

NGINX vs. Apache: Community, Support, and ResourcesNGINX vs. Apache: Community, Support, and ResourcesMay 11, 2025 am 12:19 AM

The differences between NGINX and Apache in terms of community, support and resources are as follows: 1. Although the NGINX community is small, it is active and professional, and official support provides advanced features and professional services through NGINXPlus. 2.Apache has a huge and active community, and official support is mainly provided through rich documentation and community resources.

NGINX Unit: An Introduction to the Application ServerNGINX Unit: An Introduction to the Application ServerMay 10, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports a variety of programming languages ​​and frameworks, such as Python, PHP, Java, Go, etc. 1. It supports dynamic configuration and can adjust application configuration without restarting the server. 2.NGINXUnit supports multi-language applications, simplifying the management of multi-language environments. 3. With configuration files, you can easily deploy and manage applications, such as running Python and PHP applications. 4. It also supports advanced configurations such as routing and load balancing to help manage and scale applications.

Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.