Telegraf无法连接Docker套接字问题求助:已挂载/var/run/docker.sock仍出现权限拒绝错误
Let’s tackle this permission denied error with the Docker socket in your Telegraf setup — it’s a common gotcha, but easy to fix once you know where to look. The core issue here is that even though you’ve mounted the Docker socket into the Telegraf container, the telegraf user inside the container doesn’t have the necessary permissions to access it. Docker sockets are owned by the docker group on the host, and by default, the Telegraf container’s user isn’t part of that group.
Here are the most reliable solutions to resolve this:
1. Add the Telegraf container to the host's Docker group
This is the recommended production-safe approach, as it avoids over-broad permission changes to the socket itself.
Using Docker Compose
Update your docker-compose.yml to include the group_add directive. First, confirm the GID of your host’s docker group (it’s usually 999, but verify first):
getent group docker | cut -d: -f3
Then add the group to your service config:
services: telegraf: # ... your existing image and other config volumes: - ./data/telegraf:/etc/telegraf - /var/run/docker.sock:/var/run/docker.sock group_add: - "999" # Replace with the GID you retrieved if it's different
Using Docker run command
If you’re using a direct docker run command, add the --group-add flag with the correct GID:
docker run -d \ -v ./data/telegraf:/etc/telegraf \ -v /var/run/docker.sock:/var/run/docker.sock \ --group-add 999 \ telegraf
2. Temporarily adjust Docker socket permissions (not recommended for production)
If you need a quick test fix, you can loosen the socket permissions. Note that this change will reset when Docker restarts, and it’s less secure because any user on the host can access the Docker daemon:
sudo chmod 666 /var/run/docker.sock
3. Customize the Telegraf image to add the user to the Docker group
For a persistent image-based solution, create a custom Dockerfile to modify the Telegraf user’s group membership:
FROM telegraf:latest USER root RUN usermod -aG docker telegraf USER telegraf
Build this image and use it in your setup instead of the official Telegraf image.
Verify the fix
After applying any of these solutions, restart the Telegraf container and check the logs again. The permission denied error should no longer appear, and the Docker input plugin should start collecting metrics as expected.
内容的提问来源于stack exchange,提问作者Dennis Roth

