All Products
Search
Document Center

Simple Log Service:Install LoongCollector on Kubernetes

Last Updated:May 27, 2026

LoongCollector is the next-generation SLS log collection agent and the successor to Logtail. Install it in a Kubernetes cluster using DaemonSet or sidecar mode.

Prerequisites

Before installing LoongCollector, verify network connectivity between your cluster nodes and the SLS endpoint.

  1. Obtain the endpoint:

    1. Log on to the Simple Log Service console. In the project list, click the destination project.

    2. Click the image icon next to the project name to open the project overview page.

    3. In the endpoint section, locate the public and private endpoints for the project's region.

  2. Run a connectivity test: Log on to a cluster node and run the following curl command. Replace ${PROJECT_NAME} and ${SLS_ENDPOINT} with your actual values.

    curl https://${PROJECT_NAME}.${SLS_ENDPOINT}
  3. Check the results:

    • If the command returns {"Error":{"Code":"OLSInvalidMethod",...}}, the network connection between your node and Simple Log Service is established.

      Note

      This error is expected — the test verifies network connectivity only. SLS returns an error because the request lacks required API parameters.

    • If the command times out or returns errors such as Connection refused, check the node's network configuration, security group rules, and DNS resolution.

Choose an installation method

Select a method based on your cluster type.

Installation method

Use cases

Install on an ACK cluster (DaemonSet mode)

Collect logs from ACK managed and dedicated clusters within the same Alibaba Cloud account and region.

Install on a self-managed cluster (DaemonSet mode)

  • Collect logs from ACK clusters across different Alibaba Cloud accounts or regions.

  • Collect logs from Kubernetes clusters in self-managed data centers.

  • Collect logs from Kubernetes clusters on other cloud providers.

Install in Sidecar mode

Collect logs from specific applications with the following requirements:

  • Resource isolation: Prevents the DaemonSet agent from affecting other pods on the node.

  • Fine-grained collection: Configure a separate collection source, filter rules, and output destination for each application.

Install on an ACK cluster (DaemonSet mode)

Note

If upgrading from logtail-ds, uninstall it before installing LoongCollector.

Install LoongCollector with one click in the ACK console. By default, it collects container logs into a project in the same account and region. For cross-account or cross-region collection, see Install on a self-managed cluster (DaemonSet mode).

Existing ACK cluster

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. On the Clusters page, click the name of your cluster. In the left navigation pane, click Components and Add-ons.

  3. On the Logs and Monitoring tab, find LoongCollector, and click Install.

  4. After installation, SLS automatically creates the following resources in the cluster's region, viewable in the Simple Log Service console.

    Type

    Parameter

    Description

    Project

    k8s-log-${cluster_id}

    A resource management unit that isolates logs from different services.

    machine group

    k8s-group-${cluster_id}

    Machine group for loongcollector-ds log collection.

    k8s-group-${cluster_id}-cluster

    Machine group for loongcollector-cluster metric collection.

    k8s-group-${cluster_id}-singleton

    Machine group for single-instance collection.

    Important

    LoongCollector does not create a LogStore named config-operation-log. If it already exists, LoongCollector does not write to it.

New ACK cluster

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. Click Create Cluster. On the Component Configurations page, select the Enable Log Service checkbox and then select either Create New Project or Use Existing Project.

    This topic covers only SLS-related configurations. Other cluster settings are documented in Create an ACK managed cluster.
  3. If you select Create Project, SLS automatically creates the following resources. You can view them in the Simple Log Service console.

    Type

    Parameter

    Description

    Project

    k8s-log-${cluster_id}

    A resource management unit that isolates logs from different services.

    machine group

    k8s-group-${cluster_id}

    Machine group for loongcollector-ds log collection.

    k8s-group-${cluster_id}-cluster

    Machine group for loongcollector-cluster metric collection.

    k8s-group-${cluster_id}-singleton

    Machine group for single-instance collection.

    Important

    LoongCollector does not create a LogStore named config-operation-log. If it already exists, LoongCollector does not write to it.

Install on a self-managed cluster (DaemonSet mode)

Use cases

  • Kubernetes clusters in self-managed data centers

  • Kubernetes clusters deployed on other cloud providers

  • Collecting container logs from Alibaba Cloud ACK clusters across different accounts or regions

Note

Ensure your self-managed cluster runs Kubernetes 1.6 or later.

Procedure

  1. Download and extract the installation package: On a machine with kubectl configured, run the command for your cluster's region.

    # Regions in Chinese mainland
    wget https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongcollector/k8s-custom-pkg/3.2.6/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh
    # Regions outside Chinese mainland
    wget https://aliyun-observability-release-ap-southeast-1.oss-ap-southeast-1.aliyuncs.com/loongcollector/k8s-custom-pkg/3.2.6/loongcollector-custom-k8s-package.tgz; tar xvf loongcollector-custom-k8s-package.tgz; chmod 744 ./loongcollector-custom-k8s-package/k8s-custom-install.sh
  2. Edit values.yaml: In the loongcollector-custom-k8s-package directory, edit ./loongcollector/values.yaml.

    Description

    values.yaml

    # ===================== Required Parameters =====================
    # The name of the Project for log collection in this cluster. Example: k8s-log-custom-sd89ehdq
    projectName: ""
    # The region of the Project. Example for Shanghai: cn-shanghai
    region: ""
    # The ID of the Alibaba Cloud account that owns the Project. Enclose the ID in quotation marks. Example: "123456789"
    aliUid: ""
    # The network type to use. Options: Internet or Intranet. Default: Internet
    net: Internet
    # The AccessKey ID and AccessKey secret of the Alibaba Cloud account or RAM user.
    accessKeyID: ""
    accessKeySecret: ""
    # A custom cluster ID. The ID can contain uppercase letters, lowercase letters, digits, and hyphens (-).
    clusterID: ""
    
    # ... Other optional parameters are omitted ...

    projectName String (Required)

    The name of the Project to which LoongCollector uploads logs. The naming conventions are as follows:

    • The Project name can contain only lowercase letters, digits, and hyphens (-).

    • It must start with a lowercase letter and end with a lowercase letter or a digit.

    • The name must be 3 to 63 characters long.

    region String (Required)

    The ID of the region where the Project is located. For a list of region IDs, see Regions.

    aliUid String (Required)

    The ID of the Alibaba Cloud account that owns the Project.

    net String (Required)

    The network type used for log data transmission.

    • Internet (default): The public network.

    • Intranet: The internal network.

    accessKeyID  String (Required)

    The AccessKey ID for the account that owns the project. For better security, use the AccessKey of a RAM user with the AliyunLogFullAccess policy. RAM user overview.

    accessKeySecret String (Required)

    The AccessKey secret for the specified AccessKey ID.

    clusterID String (Required)

    A custom ID for the cluster. The ID can contain only uppercase letters, lowercase letters, digits, and hyphens (-).

    Important

    Do not assign the same cluster ID to different Kubernetes clusters.

  3. Run the installation script: From the loongcollector-custom-k8s-package directory, run the following command to install LoongCollector.

    bash k8s-custom-install.sh install
  4. Verify the installation: Run the following command to check component status:

    # Check the pod status
    kubectl get po -n kube-system | grep loongcollector-ds

    Sample output:

    loongcollector-ds-gnmnh   1/1     Running   0    63s

    If a component fails to start (its status is not Running):

    1. Check the parameters in values.yaml.

    2. Check the image: Run the following command and check the Events section to confirm the image was pulled.

      kubectl describe pod loongcollector-ds -n kube-system
  5. After installation, SLS automatically creates the following resources, viewable in the Simple Log Service console.

    Resource type

    Resource name

    Purpose

    Project

    The projectName specified in the values.yaml file

    A resource management unit that isolates logs from different services.

    machine group

    k8s-group-${cluster_id}

    A group of nodes used for log collection.

    k8s-group-${cluster_id}-cluster

    The machine group for loongcollector-cluster. Used for metric collection.

    k8s-group-${cluster_id}-singleton

    A single-instance machine group for single-instance collection.

    Important

    LoongCollector does not create a Logstore named config-operation-log. If it already exists, LoongCollector stops writing to it.

Install in sidecar mode

Use sidecar mode for fine-grained log management, multi-tenant isolation, or lifecycle-coupled log collection. A dedicated LoongCollector container is injected into each application pod. To test the process, use the Appendix: YAML example.

1. Modify the pod YAML configuration

  1. Define shared volumes

    In spec.template.spec.volumes, add three shared volumes at the same level as containers:

    volumes:
      # Shared log directory (written by the application container, read by the sidecar)
      - name: ${shared_volume_name} # <-- The name must match the name in volumeMounts
        emptyDir: {}
      # Signal directory for inter-container communication (for graceful start/stop)
      - name: tasksite
        emptyDir:
          medium: Memory  # Use memory as the medium for better performance
          sizeLimit: "50Mi"
      # Shared host time zone configuration: Synchronizes the time zone for all containers in the pod
      - name: tz-config # <-- The name must match the name in volumeMounts
        hostPath:
          path: /usr/share/zoneinfo/Asia/Shanghai  # Modify the time zone as needed
    
  2. Configure application container mounts

    In the volumeMounts section of your application container, such as your-business-app-container, add the following volume mounts:

    Ensure that the application container writes logs to the ${shared_volume_path} directory so that LoongCollector can collect them.
    volumeMounts:
      # Mount the shared log volume to the application log output directory
      - name: ${shared_volume_name}
        mountPath: ${shared_volume_path}  # Example: /var/log/app
      # Mount the communication directory
      - name: tasksite
        mountPath: /tasksite  # Shared directory for communication with the LoongCollector container
      # Mount the timezone file
      - name: tz-config
        mountPath: /etc/localtime
        readOnly: true
    
  3. Inject the LoongCollector sidecar container

    In the spec.template.spec.containers array, append the following sidecar container definition:

    - name: loongcollector
      image: aliyun-observability-release-registry.cn-shenzhen.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
      command: ["/bin/bash", "-c"]
      args:
        - |
          echo "[$(date)] LoongCollector: Starting initialization"
          # Start the LoongCollector service
          /etc/init.d/loongcollectord start
          # Wait for the configuration to download and the service to be ready
          sleep 15
          # Verify the service status
          if /etc/init.d/loongcollectord status; then
            echo "[$(date)] LoongCollector: Service started successfully"
            touch /tasksite/cornerstone
          else
            echo "[$(date)] LoongCollector: Failed to start service"
            exit 1
          fi
          # Wait for the application container to complete (via the tombstone file signal)
          echo "[$(date)] LoongCollector: Waiting for application container to complete"
          until [[ -f /tasksite/tombstone ]]; do
            sleep 2
          done
          # Allow time to upload remaining logs
          echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
          sleep 30
          # Stop the service
          echo "[$(date)] LoongCollector: Stopping service"
          /etc/init.d/loongcollectord stop
          echo "[$(date)] LoongCollector: Shutdown complete"
      # health check
      livenessProbe:
        exec:
          command: ["/etc/init.d/loongcollectord", "status"]
        initialDelaySeconds: 30
        periodSeconds: 10
        timeoutSeconds: 5
        failureThreshold: 3
      # resource configuration
      resources:
        requests:
          cpu: "100m"
          memory: "128Mi"
        limits:
          cpu: "2000m"
          memory: "2048Mi"
      # environment variable configuration
      env:
        - name: ALIYUN_LOGTAIL_USER_ID
          value: "${your_aliyun_user_id}"
        - name: ALIYUN_LOGTAIL_USER_DEFINED_ID
          value: "${your_machine_group_user_defined_id}"
        - name: ALIYUN_LOGTAIL_CONFIG
          value: "/etc/ilogtail/conf/${your_region_config}/ilogtail_config.json"
        # Enable full drain mode to ensure all logs are sent before the pod terminates
        - name: enable_full_drain_mode
          value: "true"  
        # Append pod environment information as log tags
        - name: ALIYUN_LOG_ENV_TAGS
          value: "_pod_name_|_pod_ip_|_namespace_|_node_name_|_node_ip_"
        # Automatically inject pod and node metadata as log tags
        - name: "_pod_name_"
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: "_pod_ip_"
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: "_namespace_"
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: "_node_name_"
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: "_node_ip_"
          valueFrom:
            fieldRef:
              fieldPath: status.hostIP
      # Volume mounts (shared with the application container)
      volumeMounts:
        # Read-only mount for the application log directory
        - name: ${shared_volume_name} # <-- Shared log directory name
          mountPath: ${dir_containing_your_files} # <-- Path to the shared directory in the sidecar
          readOnly: true
        # Mount the communication directory
        - name: tasksite
          mountPath: /tasksite
        # Mount the timezone
        - name: tz-config
          mountPath: /etc/localtime
          readOnly: true
    

2. Adapt the application container lifecycle logic

Depending on the workload type, modify the application container to support a coordinated exit with the sidecar:

Short-lived tasks (Job/CronJob)

# 1. Wait for LoongCollector to be ready
echo "[$(date)] Application: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do
  sleep 1
done
echo "[$(date)] Application: LoongCollector is ready, starting application logic"
# 2. Execute core application logic (ensure logs are written to the shared directory)
echo "Hello, World!" >> /app/logs/business.log
# 3. Save the exit code
retcode=$?
echo "[$(date)] Application: Task completed with exit code: $retcode"
# 4. Notify LoongCollector that the application task is complete
touch /tasksite/tombstone
echo "[$(date)] Application: Tombstone created, exiting"
exit $retcode

Long-lived services (Deployment / StatefulSet)

# Define the signal handler function
_term_handler() {
    echo "[$(date)] [nginx-demo] Caught SIGTERM, starting graceful shutdown..."
    # Send a QUIT signal to Nginx for a graceful stop
    if [ -n "$NGINX_PID" ]; then
        kill -QUIT "$NGINX_PID" 2>/dev/null || true
        echo "[$(date)] [nginx-demo] Sent SIGQUIT to Nginx PID: $NGINX_PID"
        # Wait for Nginx to stop gracefully
        wait "$NGINX_PID"
        EXIT_CODE=$?
        echo "[$(date)] [nginx-demo] Nginx stopped with exit code: $EXIT_CODE"
    fi
    # Notify LoongCollector that the application container has stopped
    echo "[$(date)] [nginx-demo] Writing tombstone file"
    touch /tasksite/tombstone
    exit $EXIT_CODE
}
# Register the signal handler
trap _term_handler SIGTERM SIGINT SIGQUIT
# Wait for LoongCollector to be ready
echo "[$(date)] [nginx-demo]: Waiting for LoongCollector to be ready..."
until [[ -f /tasksite/cornerstone ]]; do 
    sleep 1
done
echo "[$(date)] [nginx-demo]: LoongCollector is ready, starting application logic"
# Start Nginx
echo "[$(date)] [nginx-demo] Starting Nginx..."
nginx -g 'daemon off;' &
NGINX_PID=$!
echo "[$(date)] [nginx-demo] Nginx started with PID: $NGINX_PID"
# Wait for the Nginx process
wait $NGINX_PID
EXIT_CODE=$?
# Also notify LoongCollector if the exit was not caused by a signal
if [ ! -f /tasksite/tombstone ]; then
    echo "[$(date)] [nginx-demo] Unexpected exit, writing tombstone"
    touch /tasksite/tombstone
fi
exit $EXIT_CODE

3. Set the termination grace period

In spec.template.spec, set a termination grace period that is long enough to allow LoongCollector to upload all remaining logs.

spec:
  # ... Your other existing spec configurations ...
  template:
    spec:
      terminationGracePeriodSeconds: 600  # 10-minute graceful stop period

4. Variables

Parameter

Description

${your_aliyun_user_id}

The ID of your Alibaba Cloud account. For more information, see Configure user identifiers.

${your_machine_group_user_defined_id}

A custom identifier used to create a machine group. Example: nginx-log-sidecar.

Important

Ensure that this identifier is unique within the Project's region.

${your_region_config}

The configuration that corresponds to your Log Service Project's region and network access type. For information about regions, see Service regions.

Example: If your Project is in the China (Hangzhou) region, use cn-hangzhou for Alibaba Cloud internal network access or cn-hangzhou-internet for public network access.

${shared_volume_name}

A custom name for the shared volume.

Important

The name in volumeMounts must match the name in volumes. This ensures both containers mount the same shared volume.

${dir_containing_your_files}

The mount path in the LoongCollector container where the text logs are located.

5. Apply configuration and verify

  1. Run the following command to deploy the changes:

    kubectl apply -f <YOUR-YAML>
  2. Check the pod status to confirm that the LoongCollector container was injected successfully:

    kubectl describe pod <YOUR-POD-NAME>

    If you see two containers (the application container and loongcollector) and their status is Running, the injection is successful.

6. Create a custom identifier machine group

  1. Log on to the Simple Log Service console and click the target project.

  2. In the left navigation bar, select imageResources > Machine Groups, and click Machine Group > Create Machine Group to the right of Machine Groups.

  3. In the Create Machine Group dialog box, configure the following parameters and click OK.

    • Name: The name of the machine group. It cannot be modified after creation. The naming conventions are as follows:

      • Can contain only lowercase letters, digits, hyphens (-), and underscores (_).

      • Must start and end with a lowercase letter or a digit.

      • Must be 2 to 128 characters in length.

    • Machine Group Identifier: Select Custom Identifier.

    • Custom Identifier: Enter the value of the ALIYUN_LOGTAIL_USER_DEFINED_ID  environment variable that you set for the LoongCollector container in 1. Modify the service Pod YAML configuration. The value must be an exact match, or the association will fail.

  4. After the machine group is created, check its heartbeat status by clicking its name and viewing the status area.

    • OK: LoongCollector has successfully connected to Simple Log Service and registered the machine group.

    • FAIL:

Each pod runs its own LoongCollector instance. Use a unique custom identifier per application or environment for granular management.

FAQ

Cross-account or cross-region collection

By default, LoongCollector installed from the ACK console collects container logs to an SLS project in the same account. To collect cross-account or cross-region, use one of the following methods:

Method 1: Uninstall and reinstall loongcollector.

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. On the Clusters page, click the name of your cluster. In the left navigation pane, click Components and Add-ons.

  3. On the Logs and Monitoring tab, find loongcollector and click Uninstall.

  4. Reinstall using the Install on a self-managed cluster (DaemonSet mode) procedure.

Method 2: Update the Helm configuration and redeploy loongcollector.

  1. Log on to the ACK console. In the left-side navigation pane, choose Apply > Helm.

  2. On the Helm page, find loongcollector and click Update in the Actions column. On the Update Release page, modify the parameters as shown in the table below and click OK.

    Cluster and project

    Parameter

    Same account, different region

    region: The RegionID of the region where the project is located.

    net: Set the value to internet. Data cannot be transferred between different regions over an intranet.

    Different account, same region

    aliUid: The Alibaba Cloud account ID that owns the Simple Log Service project. Separate multiple account IDs with a comma (,).

    net: Set the value to intranet. Data transfer within the same region is more efficient over the intranet.

    Different account, different region

    aliUid: The Alibaba Cloud account ID that owns the Simple Log Service project. Separate multiple account IDs with a comma (,).

    region: The RegionID of the region where the project is located.

    net: Set the value to internet. Data cannot be transferred between different regions over an intranet.

  3. Create a machine group:

    1. Log on to the Simple Log Service console and click the target project.

    2. In the left-side navigation pane, choose imageResources > > Machine Groups. Next to Machine Groups, choose Machine Group > > Create Machine Group.

    3. In the Create Machine Group dialog box, configure the following parameters and click OK.

      1. Enter a name for the machine group.

      2. For Machine Group Identifier, select Custom Identifier.

      3. Custom identifier: k8s-group-${cluster_id}. Replace ${cluster_id} with the actual clusterID of the cluster.

    4. After the machine group is created, find it in the machine group list and click its name. In the Machine Group Configurations > > Machine Group Status section, check the Heartbeat status. A Heartbeat status of OK indicates that the machine group is operating correctly. If the status is not OK, verify that the user and user-defined identifiers are correct.

  4. After you finish the modifications, click  Update .


Log collection for other clusters

Next steps

After installing LoongCollector, review Collect container logs from a Kubernetes cluster for core concepts and best practices, then create a collection configuration:

Appendix: YAML examples

Complete YAML configurations for a Kubernetes Job and a Deployment with a LoongCollector sidecar container.

Before you start, replace the following three placeholders:

  1. Replace ${your_aliyun_user_id} with the UID of your Alibaba Cloud account.

  2. Replace ${your_machine_group_user_defined_id} with the custom ID of the machine group that you created in Step 3. The ID must be an exact match.

  3. Replace ${your_region_config} with the configuration name that matches the region and network type of your Log Service (SLS) Project.

    For example, for a Project in the China (Hangzhou) region, use cn-hangzhou for internal network access or cn-hangzhou-internet for public network access.

Short-lived tasks (Job/CronJob)

apiVersion: batch/v1
kind: Job
metadata:
  name: demo-job
spec:
  backoffLimit: 3                   
  activeDeadlineSeconds: 3600        
  completions: 1                     
  parallelism: 1                    
  template:
    spec:
      restartPolicy: Never         
      terminationGracePeriodSeconds: 300 
      containers:
        # Application container
        - name: demo-job
          image: debian:bookworm-slim
          command: ["/bin/bash", "-c"]
          args:
            - |
              # Wait for LoongCollector to be ready.
              echo "[$(date)] Business: Waiting for LoongCollector to be ready..."
              until [[ -f /tasksite/cornerstone ]]; do 
                sleep 1
              done
              echo "[$(date)] Business: LoongCollector is ready, starting business logic"
              # Run the application logic.
              echo "Hello, World!" >> /app/logs/business.log
              # Save the exit code.
              retcode=$?
              echo "[$(date)] Business: Task completed with exit code: $retcode"
              # Notify LoongCollector that the task is finished.
              touch /tasksite/tombstone
              echo "[$(date)] Business: Tombstone created, exiting"
              exit $retcode
          # Resource requests and limits
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "500"
              memory: "512Mi"
          # volume mounts
          volumeMounts:
            - name: app-logs
              mountPath: /app/logs
            - name: tasksite
              mountPath: /tasksite
        # LoongCollector sidecar container
        - name: loongcollector
          image: aliyun-observability-release-registry.cn-hongkong.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
          command: ["/bin/bash", "-c"]
          args:
            - |
              echo "[$(date)] LoongCollector: Starting initialization"
              # Start the LoongCollector service.
              /etc/init.d/loongcollectord start
              # Wait for the configuration to download and the service to be ready.
              sleep 15
              # Verify the service status.
              if /etc/init.d/loongcollectord status; then
                echo "[$(date)] LoongCollector: Service started successfully"
                touch /tasksite/cornerstone
              else
                echo "[$(date)] LoongCollector: Failed to start service"
                exit 1
              fi
              # Wait for the application container to finish.
              echo "[$(date)] LoongCollector: Waiting for business container to complete"
              until [[ -f /tasksite/tombstone ]]; do 
                sleep 2
              done
              echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
              # Allow sufficient time to send remaining logs.
              sleep 30
              echo "[$(date)] LoongCollector: Stopping service"
              /etc/init.d/loongcollectord stop
              echo "[$(date)] LoongCollector: Shutdown complete"
          # health check
          livenessProbe:
            exec:
              command: ["/etc/init.d/loongcollectord", "status"]
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 3
          # Resource requests and limits
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "500m"
              memory: "512Mi"
          # environment variables
          env:
            - name: ALIYUN_LOGTAIL_USER_ID
              value: "your-user-id"
            - name: ALIYUN_LOGTAIL_USER_DEFINED_ID
              value: "your-user-defined-id"
            - name: ALIYUN_LOGTAIL_CONFIG
              value: "/etc/ilogtail/conf/cn-hongkong/ilogtail_config.json"
            - name: ALIYUN_LOG_ENV_TAGS
              value: "_pod_name_|_pod_ip_|_namespace_|_node_name_"
            # Inject pod metadata.
            - name: "_pod_name_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: "_pod_ip_"
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: "_namespace_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: "_node_name_"
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
          # volume mounts
          volumeMounts:
            - name: app-logs
              mountPath: /app/logs
              readOnly: true
            - name: tasksite
              mountPath: /tasksite
            - name: tz-config
              mountPath: /etc/localtime
              readOnly: true
      # Volume definitions
      volumes:
        - name: app-logs
          emptyDir: {}
        - name: tasksite
          emptyDir:
            medium: Memory
            sizeLimit: "10Mi"
        - name: tz-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Shanghai

Long-lived services (Deployment / StatefulSet)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-demo
  namespace: production
  labels:
    app: nginx-demo
    version: v1.0.0
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1      
      maxSurge: 1          
  selector:
    matchLabels:
      app: nginx-demo
  template:
    metadata:
      labels:
        app: nginx-demo
        version: v1.0.0    
    spec:
      terminationGracePeriodSeconds: 600  # 10-minute graceful shutdown period
      containers:
        # Application container - Web application
        - name: nginx-demo
          image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6          
          # Startup command and signal handling
          command: ["/bin/sh", "-c"]
          args:
            - |
              # Define the signal handler.
              _term_handler() {
                  echo "[$(date)] [nginx-demo] Caught SIGTERM, starting graceful shutdown..."
                  # Send the QUIT signal to Nginx for a graceful stop.
                  if [ -n "$NGINX_PID" ]; then
                      kill -QUIT "$NGINX_PID" 2>/dev/null || true
                      echo "[$(date)] [nginx-demo] Sent SIGQUIT to Nginx PID: $NGINX_PID"
                      # Wait for Nginx to stop gracefully.
                      wait "$NGINX_PID"
                      EXIT_CODE=$?
                      echo "[$(date)] [nginx-demo] Nginx stopped with exit code: $EXIT_CODE"
                  fi
                  # Notify LoongCollector that the application container has stopped.
                  echo "[$(date)] [nginx-demo] Writing tombstone file"
                  touch /tasksite/tombstone
                  exit $EXIT_CODE
              }
              # Register the signal handler.
              trap _term_handler SIGTERM SIGINT SIGQUIT
              # Wait for LoongCollector to be ready.
              echo "[$(date)] [nginx-demo]: Waiting for LoongCollector to be ready..."
              until [[ -f /tasksite/cornerstone ]]; do 
                sleep 1
              done
              echo "[$(date)] [nginx-demo]: LoongCollector is ready, starting business logic"
              # Start Nginx.
              echo "[$(date)] [nginx-demo] Starting Nginx..."
              nginx -g 'daemon off;' &
              NGINX_PID=$!
              echo "[$(date)] [nginx-demo] Nginx started with PID: $NGINX_PID"
              # Wait for the Nginx process to exit.
              wait $NGINX_PID
              EXIT_CODE=$?
              # If the process exits without a signal, notify LoongCollector.
              if [ ! -f /tasksite/tombstone ]; then
                  echo "[$(date)] [nginx-demo] Unexpected exit, writing tombstone"
                  touch /tasksite/tombstone
              fi
              exit $EXIT_CODE
          # Resource requests and limits
          resources:
            requests:
              cpu: "200m"
              memory: "256Mi"
            limits:
              cpu: "1000m"
              memory: "1Gi"
          # volume mounts
          volumeMounts:
            - name: nginx-logs
              mountPath: /var/log/nginx
            - name: tasksite
              mountPath: /tasksite
            - name: tz-config
              mountPath: /etc/localtime
              readOnly: true
        # LoongCollector sidecar container
        - name: loongcollector
          image: aliyun-observability-release-registry.cn-shenzhen.cr.aliyuncs.com/loongcollector/loongcollector:v3.1.1.0-20fa5eb-aliyun
          command: ["/bin/bash", "-c"]
          args:
            - |
              echo "[$(date)] LoongCollector: Starting initialization"
              # Start the LoongCollector service.
              /etc/init.d/loongcollectord start
              # Wait for the configuration to download and the service to be ready.
              sleep 15
              # Verify the service status.
              if /etc/init.d/loongcollectord status; then
                echo "[$(date)] LoongCollector: Service started successfully"
                touch /tasksite/cornerstone
              else
                echo "[$(date)] LoongCollector: Failed to start service"
                exit 1
              fi
              # Wait for the application container to finish.
              echo "[$(date)] LoongCollector: Waiting for business container to complete"
              until [[ -f /tasksite/tombstone ]]; do 
                sleep 2
              done
              echo "[$(date)] LoongCollector: Business completed, waiting for log transmission"
              # Allow sufficient time to send remaining logs.
              sleep 30
              echo "[$(date)] LoongCollector: Stopping service"
              /etc/init.d/loongcollectord stop
              echo "[$(date)] LoongCollector: Shutdown complete"
          # health check
          livenessProbe:
            exec:
              command: ["/etc/init.d/loongcollectord", "status"]
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 3
          # Resource requests and limits
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "2000m"
              memory: "2048Mi"
          # environment variables
          env:
            - name: ALIYUN_LOGTAIL_USER_ID
              value: "${your_aliyun_user_id}"
            - name: ALIYUN_LOGTAIL_USER_DEFINED_ID
              value: "${your_machine_group_user_defined_id}"
            - name: ALIYUN_LOGTAIL_CONFIG
              value: "/etc/ilogtail/conf/${your_region_config}/ilogtail_config.json"
            # Enable full drain mode to send all logs when the pod stops.
            - name: enable_full_drain_mode
              value: "true"
            # Append pod environment information as log tags.
            - name: "ALIYUN_LOG_ENV_TAGS"
              value: "_pod_name_|_pod_ip_|_namespace_|_node_name_|_node_ip_"
            # Get pod and node information.
            - name: "_pod_name_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: "_pod_ip_"
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: "_namespace_"
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: "_node_name_"
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: "_node_ip_"
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
          # volume mounts
          volumeMounts:
            - name: nginx-logs
              mountPath: /var/log/nginx
              readOnly: true
            - name: tasksite
              mountPath: /tasksite
            - name: tz-config
              mountPath: /etc/localtime
              readOnly: true
      # Volume definitions
      volumes:
        - name: nginx-logs
          emptyDir: {}
        - name: tasksite
          emptyDir:
            medium: Memory
            sizeLimit: "50Mi"
        - name: tz-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Shanghai

References

Regions

  1. Log on to the Simple Log Service console. In the Project list, click the target Project.

  2. Click the image icon next to the Project name to open the project overview page.

  3. In the Basic Information section, you can view the region name of the current Project. For the mapping between region names and Region IDs, see the following table.

    A region is the physical data center location for your cloud resources. A Region ID uniquely identifies each region.

    Region name

    Region ID

    China (Qingdao)

    cn-qingdao

    China (Beijing)

    cn-beijing

    China (Zhangjiakou)

    cn-zhangjiakou

    China (Hohhot)

    cn-huhehaote

    China (Ulanqab)

    cn-wulanchabu

    China (Hangzhou)

    cn-hangzhou

    China (Shanghai)

    cn-shanghai

    China (Nanjing - Local Region - Decommissioning)

    cn-nanjing

    China (Fuzhou - Local Region - Decommissioning)

    cn-fuzhou

    China (Shenzhen)

    cn-shenzhen

    China (Heyuan)

    cn-heyuan

    China (Guangzhou)

    cn-guangzhou

    Philippines (Manila)

    ap-southeast-6

    South Korea (Seoul)

    ap-northeast-2

    Malaysia (Kuala Lumpur)

    ap-southeast-3

    Japan (Tokyo)

    ap-northeast-1

    Thailand (Bangkok)

    ap-southeast-7

    China (Chengdu)

    cn-chengdu

    Singapore

    ap-southeast-1

    Indonesia (Jakarta)

    ap-southeast-5

    China (Hong Kong)

    cn-hongkong

    Germany (Frankfurt)

    eu-central-1

    US (Virginia)

    us-east-1

    US (Silicon Valley)

    us-west-1

    UK (London)

    eu-west-1

    UAE (Dubai)

    me-east-1

    Saudi Arabia (Riyadh)

    me-central-1

Network transfer types

An endpoint is the access domain name for Simple Log Service. It is the URL used to access a project and its log data, and it is related to the region where the project is located. Simple Log Service provides private endpoints, public endpoints, and acceleration endpoints. You can view the endpoints as follows:

  1. Log on to the Simple Log Service console and click the target project in the project list.

  2. Click the image icon to the right of the project name to go to the project overview page.

  3. In the Endpoints section, you can view the endpoint information for the current project. Different network transmission methods correspond to different endpoints. A suitable network transmission method helps ensure faster and more stable log data transmission.

Network type

Applicable domain names

Description

Scenario

Alibaba Cloud private network

Private endpoint

The Alibaba Cloud private network is a gigabit shared network. Transmitting log data over the Alibaba Cloud private network is faster and more stable than over the public network. The private network includes VPCs and the classic network.

The ECS instance and the Simple Log Service project are in the same region, or the on-premises server is connected to the private network.

Note

Create a Simple Log Service project in the same region as your ECS instance. This lets you collect logs from the ECS instance over the Alibaba Cloud private network without consuming public bandwidth.

Public network

Public endpoint

When you use the public network to transmit log data, the speed and stability of data collection can be affected by network bandwidth limitations, network jitter, latency, and packet loss.

You can choose to transmit data over the public network in the following two cases:

  • The ECS instance and the Simple Log Service project are in different regions.

  • The server is from another cloud provider or an on-premises data center.

Transfer acceleration

Acceleration endpoint

This method uses Alibaba Cloud CDN points of presence (POPs) to accelerate log collection. It offers significant advantages in network latency and stability compared to public network collection. However, you are charged for the traffic.

If your business server and Simple Log Service project are in different regions, such as one in the Chinese mainland and the other outside China, you may experience high network latency and unstable transmission when using the public network. In this case, you can choose to use transfer acceleration. For more information, see Transfer acceleration.

Running modes

Feature

DaemonSet mode

Sidecar mode

Deployment method

Deploys one collection container on each node.

Deploys one collection container in each Pod.

Resource consumption

Low (shares node resources)

Higher (each Pod consumes resources independently)

Use cases

Unified, node-level log collection

Isolated log collection for specific applications

Isolation

Node-level sharing

Pod-level independence

DaemonSet mode

A LoongCollector agent is deployed on each node in the cluster to collect logs from all containers on that node. This mode features simple operations, low resource consumption, and flexible configuration, but it offers weaker isolation between tenants.

  • In DaemonSet mode, the Kubernetes cluster ensures that only one LoongCollector container runs on each node to collect logs from all containers on that node.

  • When a new node joins the cluster, Kubernetes automatically creates a LoongCollector container on it. When a node leaves the cluster, Kubernetes automatically destroys the LoongCollector container on that node. This automatic scaling means you do not need to manually manage LoongCollector instances.

image

Sidecar mode

In each pod, a LoongCollector sidecar container is injected alongside the application container. The application container's log directory is mounted as a shared volume by using a Kubernetes volume mechanism, such as emptyDir, hostPath, or a PVC. This makes the log files accessible to both the application container and the sidecar container, allowing LoongCollector to read them directly. This mode provides strong multi-tenant isolation and high performance but consumes more resources and is more complex to configure and maintain.

  • In sidecar mode, each pod runs a dedicated LoongCollector container to collect logs from all other containers within that same pod. Log collection is isolated between different pods.

  • To collect log files from other containers in the same pod, you must use a shared volume. The same volume must be mounted to both the application container and the LoongCollector container.

  • If the data volume of a single pod on a node is exceptionally large and exceeds the collection capacity of the DaemonSet agent, the sidecar mode allows you to allocate specific resources to LoongCollector, improving its collection performance and stability.

  • Serverless container environments do not have a node concept, which makes the DaemonSet deployment mode inapplicable. In these cases, the sidecar mode integrates effectively with the serverless architecture, ensuring a flexible and adaptive log collection process.

image