All Products
Search
Document Center

Simple Log Service:Installation and configuration

Last Updated:Aug 25, 2026

LoongCollector is the next-generation log collection agent for Alibaba Cloud Simple Log Service (SLS), upgrading Logtail with enhanced capabilities. You can install it in a Kubernetes cluster in DaemonSet or Sidecar mode.

Prerequisites

Before you install LoongCollector, verify network connectivity between your cluster nodes and the server-side endpoint of Simple Log Service. The nodes must reach that endpoint before log collection can report data.

  1. Obtain the service endpoint:

    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, locate the public and internal endpoints for the project's region.

  2. Run a connectivity test: Log on to the cluster node where you will install LoongCollector and run the following curl command. Replace ${ProjectName} and ${SLS_ENDPOINT} with the actual values.

    curl https://${ProjectName}.${SLS_ENDPOINT}
  3. Check the test result:

    • If the command returns {"Error":{"Code":"OLSInvalidMethod",...}}, the node has network connectivity to Simple Log Service.

      Note

      This test only verifies network-layer connectivity. The error response is expected because the request lacks required API parameters.

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

Installation methods

Choose an installation method based on your cluster type and requirements.

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 that require:

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

  • Fine-grained collection: The ability to configure a separate collection source, filtering rules, and output destination for each application.

Install on an ACK cluster (DaemonSet mode)

You can install LoongCollector with a single click in the Container Service for Kubernetes (ACK) console. By default, LoongCollector collects container logs and sends them to a Project in the same Alibaba Cloud account and region. To collect logs across accounts or regions, see Install on a self-managed cluster (DaemonSet mode).

Install on an existing ACK managed 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, Simple Log Service (SLS) automatically creates the following resources in the ACK cluster's region. You can view them in the Simple Log Service (SLS) console.

    Resource type

    Resource name

    Purpose

    Project

    k8s-log-${cluster_id}

    Isolates logs from different services.

    Machine group

    k8s-group-${cluster_id}

    The machine group for loongcollector-ds, 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 machine group for specific single-instance collection configurations.

    Important

    The LoongCollector component does not create a LogStore named config-operation-log. If this LogStore already exists, LoongCollector will not write logs to it.

Install while creating an ACK managed 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. You can then select Create a new Project or Use an existing Project.

    This topic describes only the settings for Simple Log Service (SLS). For more information about other configuration items, see Create an ACK managed cluster.
  3. When you select Create Project, Simple Log Service (SLS) automatically creates the following resources. You can view them in the Simple Log Service (SLS) console.

    Resource type

    Resource name

    Purpose

    Project

    k8s-log-${cluster_id}

    Isolates logs from different services.

    Machine group

    k8s-group-${cluster_id}

    The machine group for loongcollector-ds, 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 machine group for specific single-instance collection configurations.

    Important

    The LoongCollector component does not create a LogStore named config-operation-log. If this LogStore already exists, LoongCollector will not write logs 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

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

Note

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

Procedure

  1. Download and extract the installation package: From a machine with kubectl installed and configured, run the appropriate command for your cluster's region to download LoongCollector and its dependencies.

    # China regions
    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 the 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. Modify the configuration file values.yaml: Go to the loongcollector-custom-k8s-package directory and modify the ./loongcollector/values.yaml configuration file.

    Parameters

    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 to use. Options: Internet (public network) or Intranet (internal network). 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: ""
    
    # ... Optional parameters are omitted ...

    projectName String (Required)

    The name of the project to which LoongCollector uploads logs. The name must follow these rules:

    • Must contain only lowercase letters, digits, and hyphens (-).

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

    • Must be 3 to 63 characters in length.

    region String (Required)

    The ID of the project's region. 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 for log data transmission.

    • Internet (default): The public network.

    • Intranet: The internal network.

    accessKeyID  String (Required)

    The AccessKey ID used to access the project. We recommend that you use the AccessKey pair of a RAM user. Grant the AliyunLogFullAccess system policy to the RAM user. For more information about RAM, see Overview.

    accessKeySecret String (Required)

    The AccessKey secret that corresponds to the AccessKey ID.

    clusterID String (Required)

    A custom ID for the cluster. The ID must 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: In the loongcollector-custom-k8s-package directory, run the following command to install LoongCollector and its dependencies.

    bash k8s-custom-install.sh install
  4. Verify the installation: After the installation is complete, run the following command to check the pod 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 pod fails to start (its status is not Running):

    1. Check the configuration: Verify that the parameters in values.yaml are correct.

    2. Check the image: Run the following command and check the Events section of the output to verify the container image was pulled successfully.

      kubectl describe pod loongcollector-ds -n kube-system
  5. After LoongCollector is installed, Simple Log Service automatically creates the following resources. You can view them in the Simple Log Service console.

    Resource type

    Resource name

    Description

    Project

    The projectName value specified in the values.yaml file.

    A resource management unit that isolates logs from different services.

    Machine group

    k8s-group-${cluster_id}

    A machine group containing all nodes that collect logs.

    k8s-group-${cluster_id}-cluster

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

    k8s-group-${cluster_id}-singleton

    A single-instance machine group for specific collection configurations.

    Important

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

Install in Sidecar mode

Sidecar mode works by injecting a dedicated LoongCollector (Logtail) container into your application Pod to collect logs exclusively from that Pod. This pattern is ideal when you need fine-grained log management, multi-tenant isolation, or a tight binding between log collection and the application lifecycle. If you have not deployed an application or want to test the process, you can use the Appendix: YAML examples to quickly verify the workflow.

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. 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 SLS Project's region and network access type. 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-based machine group

  1. Log on to the Simple Log Service console, and then 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. You cannot change this name after creation. The name must meet the following requirements:

      • 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 the YAML file in 1. Modify the service Pod YAML configuration. This must be an exact match. Otherwise, the association will fail.

  4. To check the heartbeat of a machine group, click the name of the newly created machine group and find the machine group status area.

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

    • FAIL:

Each Pod has a dedicated LoongCollector instance. We recommend that you use different custom identifiers for different applications or environments for fine-grained management.

FAQ

How do I modify the LoongCollector configuration of an ACK managed cluster to collect logs across accounts or regions?

If you installed loongcollector from the Alibaba Cloud ACK console, it collects container logs by default into a Simple Log Service Project in the same Alibaba Cloud account. To collect logs across accounts or regions, use one of the following methods:

Method 1: Uninstall and reinstall

  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 the component as described in Install on a self-managed cluster (DaemonSet mode).

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 application management page, find loongcollector, and in the Actions column, click Update. On the Update Release page, modify the configurations as described in the following table, keep other configurations unchanged, and click OK.

    Cluster and project

    Parameters

    Same account, different region

    region: The Region ID of the region where the destination Project is located.

    net: Set the value to Internet. Data cannot be transferred between different regions over an internal network.

    Different account, same region

    aliUid: The account ID of the Alibaba Cloud account that owns the destination Project. Separate multiple account IDs with a comma.

    net: Set the value to Intranet. We recommend using the internal network for data transfer within the same region.

    Different account, different region

    aliUid: The account ID of the Alibaba Cloud account that owns the destination Project. Separate multiple account IDs with a comma.

    region: The Region ID of the region where the destination Project is located.

    net: Set the value to Internet. Data cannot be transferred between different regions over an internal network.

  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. To the right of Machine Groups, click 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. For Custom Identifier, enter k8s-group-${cluster_id}. Replace ${cluster_id} with the clusterID value of your cluster.

    4. After the machine group is created, find it in the list and click its name. In the Machine Group Configurations > > Machine Group Status section, check the Heartbeat status. A status of OK indicates a successful connection. If the heartbeat fails, verify that the user identifier and custom identifier are correct.

  4. After modifying the configuration, click Update.


How do I collect container logs from ACK Edge, ACK One, ACS, and ACK Serverless clusters?

How do I modify the projectName parameter of the LoongCollector component?

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

  2. On the Helm application management page, find loongcollector and click Update in the Actions column to go to the update release page.

  3. In the parameter configuration (Values) section of the target Helm Chart, modify the projectName parameter (root-level field), and then click OK.

Note

When you configure environment variables, if ALICLOUD_LOG_PROJECT is not explicitly specified, the system uses the Project parameter passed in the installation command as the default value and automatically creates LoongCollector-related configurations and the default machine group for the cluster under that Project.

Next steps

After you install LoongCollector, see Guidelines for collecting container logs from a Kubernetes cluster to understand the core principles, processes, and best practices for container log collection. Then, create a collection configuration using one of the following methods:

Appendix: YAML examples

This example shows a complete Kubernetes Deployment configuration that contains an application container (Nginx) and a LoongCollector sidecar container. Use it to collect container logs in Sidecar mode.

Before using the configuration, make the following replacements:

  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 your Log Service (SLS) project's region and network type.

    Example: If your project is 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 destination project.

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

  3. In the Basic Information section, view the region name of the current project. The following table maps region names to their corresponding Region IDs.

    A region is the geographical location of the physical data center for a cloud service. A Region ID is its unique identifier.

    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

    SAU (Riyadh)

    me-central-1

Loongcollector network transmission types

An endpoint is the access domain name for SLS. It is the URL used to access a project and its log data. The endpoint is specific to the region where the project is located. SLS provides private endpoints, public endpoints, and transfer acceleration endpoints. View the endpoints as follows:

  1. Log on to the SLS console. In the project list, click the target project.

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

  3. In the Access Endpoints section, view the endpoint information for the current project. Different network transfer methods correspond to different endpoints. Choosing the right network transfer method helps ensure faster and more stable log data transmission.

Network type

Corresponding endpoint type

Description

Scenarios

Alibaba Cloud internal network

Private endpoint

The Alibaba Cloud internal network is a gigabit shared network. Transferring log data over the internal network is faster and more stable than over the public internet. The internal network includes VPC and the classic network.

The ECS instance and the SLS project are in the same region, or you have connected your on-premises server to the internal network.

Note

Create an SLS project in the same region as your ECS instance. This lets you collect logs from the ECS instance over the Alibaba Cloud internal network without consuming public bandwidth.

Public internet

Public endpoint

When you transfer log data over the public internet, the speed and stability of data collection can be affected by bandwidth limits, network jitter, latency, and packet loss.

Transfer data over the public internet in the following two cases.

  • The ECS instance and the SLS project are in different regions.

  • The server is hosted by another cloud provider or in your on-premises data center.

Transfer acceleration

Transfer acceleration endpoint

Using Alibaba Cloud CDN edge nodes to accelerate log collection offers significant advantages in network latency and stability compared to collection over the public internet, but the traffic incurs additional charges.

If your application server and SLS project are in Chinese and international regions respectively, transferring data over the public internet may cause high latency and instability. Use transfer acceleration to transfer data in this case. For more information, see Transfer acceleration.

Loongcollector running modes

Attribute

DaemonSet mode

Sidecar mode

Deployment method

Deploys one collection container on each node.

Deploys one collection container in each pod.

Resource consumption

Low (shared 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

How DaemonSet mode works

Deploys a LoongCollector agent on each node to collect logs from all containers on that node. Offers simple operations, low resource consumption, and flexible configuration, but weaker tenant isolation.

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

  • Kubernetes automatically creates and destroys LoongCollector containers as nodes join or leave the cluster, eliminating manual instance management.

image

How Sidecar mode works

Injects a LoongCollector sidecar alongside the application container in each pod. The application's log directory is shared via a Kubernetes volume (emptyDir, hostPath, or PVC), allowing LoongCollector to read log files directly. Provides strong tenant isolation and high performance, but consumes more resources.

  • In sidecar mode, each pod runs a dedicated LoongCollector container. Log collection is isolated between pods.

  • A shared volume must be mounted to both the application and LoongCollector containers for log file access.

  • When a pod's log volume exceeds DaemonSet capacity, sidecar mode lets you allocate dedicated resources to LoongCollector.

  • Serverless environments lack nodes, making DaemonSet inapplicable. Sidecar mode integrates directly with serverless architectures.

image