IMD SolutionComputing LibraryShop main store

How-to

Connect a Go app to InfluxDB on ctrlX CORE

Edge computing and IIoT Published 8 min read By IMD Solution engineering team

Short answer

To connect a Go app in the port-forwarded ctrlX App Build Environment to InfluxDB on ctrlX COREvirtual, forward TCP port 8086 to the host PC in ctrlX WORKS and target the host loopback gateway 10.0.2.2 on that port. Initialize the influxdb-client-go v2 module on Go 1.17 or later with an organization, bucket, and scoped v2 API token, then read Flux query rows with result.Next().

A workstation monitor showing a time-series chart with a list of measurements and tags, beside a fanless edge computer with a network lead
On this page
  1. How do you forward TCP port 8086 from ctrlX COREvirtual to your host PC?
  2. What organization, bucket, and API token setup does InfluxDB on ctrlX CORE require?
  3. Which Go version and client options initialize the InfluxDB v2 connection?
  4. How do you write test points and read Flux query rows with result.Next()?
  5. How much query payload does a one-hour Flux window transfer?
  6. What do timeout and unauthorized errors from the Go client mean?
  7. What changes when moving the Go app from ctrlX COREvirtual to a physical ctrlX CORE?
  8. Questions asked

To connect a Go app inside the port-forwarded ctrlX App Build Environment to InfluxDB on ctrlX COREvirtual, forward TCP port 8086 to your host PC in ctrlX WORKS and set the client URL to http://10.0.2.2:8086. Create an organization, a bucket, and a scoped v2 API token in the InfluxDB web interface, initialize github.com/influxdata/influxdb-client-go/v2 with influxdb2.NewClientWithOptions, and read Flux query rows with result.Next(). Below are the exact port-forwarding steps, Go client setup, verification workflow, payload math, error checks, and physical-controller changes.

How do you forward TCP port 8086 from ctrlX COREvirtual to your host PC? #

Open the port-forwarding settings for your ctrlX COREvirtual instance in ctrlX WORKS, map guest TCP port 8086 to the same host port, and point your Go app inside the App Build Environment at http://10.0.2.2:8086. ctrlX COREvirtual and the Ubuntu-based App Build Environment run as separate port-forwarded virtual machines rather than sharing one network stack.

That guest separation produces the same reachability failure analyzed in why Node-RED on ctrlX COREvirtual cannot reach a host PostgreSQL instance: calling localhost inside one VM never exits that guest. Under QEMU user-mode networking, 10.0.2.2 routes traffic from the App Build Environment back to the host PC loopback adapter, where the ctrlX WORKS forwarding rule delivers it to InfluxDB on the virtual controller.

Configure and test the forwarded path before writing Go code:

  1. Open the port-forwarding settings for your virtual controller in ctrlX WORKS, stopping the virtual control first if your release locks forwarding rules while running.
  2. Add a TCP forwarding rule mapping the guest InfluxDB port to port 8086 on your host PC loopback interface, or to another unused host port if a local service already listens there.
  3. Start ctrlX COREvirtual, confirm the InfluxDB app is running, and verify that an HTTP request from your host PC reaches the forwarded endpoint.
  4. From a terminal inside the App Build Environment, verify that an HTTP request to the virtual gateway URL reaches InfluxDB before running your Go binary.

What organization, bucket, and API token setup does InfluxDB on ctrlX CORE require? #

Every InfluxDB v2 Go client connection requires three provisioned objects on the target controller: an organization name, a target bucket name, and a v2 API token with explicit read and write grants scoped to that bucket. This workflow applies to the InfluxDB v2 app (tested on InfluxDB app v2.4.0 running on ctrlX COREvirtual V1.20), using the token-scoped authorization model explained in connecting Node-RED to InfluxDB 2.6 with the v2 API. If the InfluxDB web UI returns a 404 immediately after app installation, clear that service routing fault first using the ctrlX CORE InfluxDB web UI 404 fix.

Provision your database objects in this order:

  1. Sign in to the InfluxDB web interface on your virtual or physical controller and record the exact case-sensitive organization name.
  2. Create a dedicated bucket for your Go app telemetry (for example TestBucket) and set its retention period to match your storage capacity.
  3. Generate a custom API token granted only read and write access to that single bucket, and copy the secret immediately because InfluxDB displays it only once.
  4. Pass the organization, bucket, and API token into your App Build Environment through environment variables or runtime configuration instead of hard-coding credentials into committed Go source files.

Which Go version and client options initialize the InfluxDB v2 connection? #

Import github.com/influxdata/influxdb-client-go/v2 on Go 1.17 or later (required for releases v2.13.0 and v2.14.0), chain transport settings onto influxdb2.DefaultOptions(), and construct the client by calling influxdb2.NewClientWithOptions(url, token, options). Per the InfluxDB Go client v2 documentation, optional transport settings chain directly onto influxdb2.DefaultOptions(). Enable SetUseGZip(true) to compress HTTP writes and query responses on constrained links, and for isolated lab tests against self-signed HTTPS certificates the library exposes SetTLSConfig(&tls.Config{InsecureSkipVerify: true}).

Never deploy InsecureSkipVerify: true on a production plant network. Disabling certificate validation defeats server authentication under TLS (IETF RFC 8446) and exposes your API token to interception; on a deployed controller, validate server certificates against your site certificate authority instead.

This snippet declares illustrative Go variables with explicit types and initial values before calling the documented client constructor:

package main

import (
	"crypto/tls"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)

func newDevelopmentClient() {
	// Illustrative example variables for a port-forwarded ctrlX COREvirtual session
	var (
		influxURL   string = "http://10.0.2.2:8086"
		influxToken string = "example-bucket-scoped-api-token"
		useLabTLS   bool   = false
	)

	// Documented client option builder and constructor from influxdb-client-go v2
	options := influxdb2.DefaultOptions().
		SetUseGZip(true)
	if useLabTLS {
		// Lab-only override for self-signed certificates; omit in production
		options.SetTLSConfig(&tls.Config{InsecureSkipVerify: true})
	}

	client := influxdb2.NewClientWithOptions(influxURL, influxToken, options)
	_ = client
}

Run go version in the App Build Environment before fetching modules to verify your toolchain meets the minimum Go release. A clean build proves only that Go resolved the module dependencies; verify live transport reachability and token authorization by executing a write-and-query test.

How do you write test points and read Flux query rows with result.Next()? #

Write one known measurement, field, value, and timestamp through your client's organization-scoped write interface, execute a matching Flux query with queryAPI.Query(context.Background(), fluxQuery), and step through every returned record using result.Next(). Distinguish three milestones during bring-up in Visual Studio Code inside the App Build Environment: HTTP reachability, a confirmed bucket write, and a confirmed Flux readback.

Obtain the organization-scoped write and query handles from client per your installed module version's documentation, then execute and iterate the Flux query as shown below:

// Illustrative Flux query targeting an example bucket, measurement, and field
var fluxQuery string = `from(bucket: "TestBucket") |> range(start: -1h) |> filter(fn: (r) => r["_measurement"] == "metric") |> filter(fn: (r) => r["_field"] == "sampleValue")`

// Documented query execution and row iteration calls (queryAPI bound to your organization)
result, err := queryAPI.Query(context.Background(), fluxQuery)
if err != nil {
	fmt.Printf("Request error: %s\n", err.Error())
	return
}
for result.Next() {
	fmt.Printf("row: %s\n", result.Record().String())
}
if result.Err() != nil {
	fmt.Printf("Query error: %s\n", result.Err().Error())
}

Prove end-to-end persistence with this verification sequence:

  1. Confirm main.go imports context, fmt, and github.com/influxdata/influxdb-client-go/v2 and binds your provisioned organization, bucket, and scoped API token.
  2. Write a single identifiable test point using measurement metric, field sampleValue, a distinct numeric value such as 42.5, and the current UTC timestamp before running the query.
  3. Run go run main.go from the Visual Studio Code terminal inside the App Build Environment.
  4. Confirm stdout prints a row: line showing metric, sampleValue, 42.5, and the matching timestamp with both err and result.Err() nil.

Always inspect result.Err() after the for result.Next() loop finishes so mid-stream Flux parsing or transport failures never fail silently. Actual returned row counts depend on write triggers, buffering, bucket retention, and active Flux filters.

How much query payload does a one-hour Flux window transfer? #

Under an illustrative response size of 80 bytes/row uncompressed, a one-hour Flux window transfers 288 kB for one field logged at 1 sample/s, but climbs to 14.4 MB when polling 10 fields at 5 samples/s. The starter range(start: -1h) filter works well for slow diagnostics, yet higher scan rates multiply response size and transfer latency across the virtual bridge or plant LAN.

Using two illustrative inputs (that uncompressed row size and 10,000,000 bytes/s effective TCP throughput, representing 80% payload efficiency on a 100 Mbit/s Ethernet link) rather than documented InfluxDB limits, the arithmetic scales as follows:

  • Single-field baseline over one hour (3,600 s): 1 field * 1 sample/s * 3,600 s = 3,600 rows. Multiplying by the assumed row size yields 3,600 rows * 80 bytes/row = 288,000 bytes (288 kB at 1,000 bytes/kB), giving a wire transfer time of 288,000 bytes / 10,000,000 bytes/s = 0.0288 s (28.8 ms), excluding server execution.
  • Multi-field high-rate pull over the same window: 10 fields * 5 samples/s * 3,600 s = 180,000 rows, producing 14,400,000 bytes (14.4 MB) uncompressed and 1.44 s of wire transfer at the assumed throughput before Go parses the Flux records.
  • Narrowed 5 min (300 s) pull at that scan rate: 10 fields * 5 samples/s * 300 s = 15,000 rows, cutting payload by 12x to 1,200,000 bytes (1.2 MB) and wire time to 0.12 s (120 ms).

Keep an uncompressed one-hour raw query only when returned rows stay in the low thousands. Once multi-field polling pushes raw responses into multiple megabytes, shorten the Flux time window, narrow your measurement and field predicates, or enable SetUseGZip(true) on influxdb2.DefaultOptions() so repetitive HTTP text compresses in transit.

What do timeout and unauthorized errors from the Go client mean? #

A context deadline exceeded (Client.Timeout exceeded while awaiting headers) error means InfluxDB never returned HTTP headers due to routing, port forwarding, or firewall blocking, whereas unauthorized proves transport reachability and isolates the fault to your API token, organization, or bucket permissions. Diagnose from the exact Go error string before changing code so you separate network reachability from credential or filter faults.

Observed client symptom Failing stage Concrete check and fix
context deadline exceeded (Client.Timeout exceeded while awaiting headers) TCP/HTTP transport Verify the ctrlX WORKS port-forwarding rule, confirm the Go client targets the virtual gateway URL rather than guest localhost, check host firewall rules, and verify the InfluxDB app is running.
unauthorized on write or query API token or bucket grant Re-copy or regenerate the API token without stray whitespace, confirm exact organization casing, and grant both read and write permissions on the target bucket.
Zero rows with nil err and nil result.Err() Write confirmation or Flux filter Confirm the test point committed, check exact bucket, measurement, and field spelling, and verify clock sync between the build VM and ctrlX COREvirtual so timestamps fall inside the Flux range window.
TLS handshake or certificate error on HTTPS TLS certificate validation Match http versus https to the InfluxDB listener and install your site certificate authority rather than leaving verification disabled in production.

What changes when moving the Go app from ctrlX COREvirtual to a physical ctrlX CORE? #

When moving your compiled Go app from the App Build Environment onto a physical ctrlX CORE, replace the virtual gateway URL with the on-device loopback or target controller address, remove any lab TLS verification overrides, and verify external storage for InfluxDB. The host-loopback gateway address exists only inside the port-forwarded build VM; leaving it in production guarantees immediate connection timeouts.

Load the endpoint URL, organization, bucket, and API token from runtime configuration or environment variables so one compiled Go binary runs across development, staging, and production targets. Match your endpoint and hardening steps to the target deployment topology:

  1. App Build Environment targeting ctrlX COREvirtual: Keep the ctrlX WORKS forwarding rule active, use the virtual gateway address, and treat any self-signed TLS override strictly as temporary lab configuration.
  2. Go app running directly on the physical ctrlX CORE alongside InfluxDB: Target the controller's local loopback endpoint with no port-forwarding hop, and confirm InfluxDB writes to persistent external media as covered in storing InfluxDB data on an SD card in ctrlX CORE.
  3. Go app running on an external edge host targeting ctrlX CORE over Ethernet: Target the controller's plant-network address over HTTPS with verified certificates, restrict the InfluxDB firewall port to authorized hosts, and repeat the known-value write-and-readback test against the live controller before production release.

Questions asked

Can you call the InfluxDB HTTP API directly from Go without the client library?

Yes, InfluxDB v2 exposes a standard HTTP REST interface, so standard Go HTTP requests can submit writes and Flux queries directly using your API token for authentication. Using the official Go client library is still preferred for production apps because it handles gzip compression, transport options, and structured Flux row iteration automatically, while standalone HTTP requests remain useful for isolating network or credential faults with an external API testing tool.

Why does localhost inside the App Build Environment fail to reach ctrlX COREvirtual?

Inside a Linux virtual machine, the loopback address 127.0.0.1 routes strictly to services listening inside that same guest kernel. Because the Ubuntu App Build Environment and ctrlX COREvirtual run as separate virtual machines, forwarding the database port to the host computer only exposes it on the host loopback adapter. Traffic must exit the build virtual machine through its user-mode virtual gateway before the host operating system can forward it into the virtual controller.

Should you reuse one InfluxDB client instance across goroutines in a Go app?

Create one shared client instance at application startup and reuse it across concurrent goroutines rather than opening a new client on every polling cycle. Reusing one client preserves the underlying Go HTTP transport connection pool, avoids repeated TCP handshakes and ephemeral port exhaustion during steady logging, and lets you close the client cleanly on process shutdown so pending operations finish before the app exits.

When should a ctrlX CORE project use a Go app instead of Node-RED or Telegraf?

Choose a compiled Go app when you need custom protocol parsing, predictable memory behavior, typed business logic, or tight packaging as a standalone app alongside your automation workload. Choose Telegraf when you only need scheduled metric forwarding from standard inputs into InfluxDB buckets, and choose Node-RED for rapid low-code flows or occasional event-driven database inserts that do not justify maintaining compiled Go code.

Keep reading

  • How-to

    Connect Node-RED to InfluxDB 2.6 with the v2 API

    Yes: node-red-contrib-influxdb writes to InfluxDB 2.6 over the v2 API. Set the configuration node to 2.0, enter the server URL and API token, then the organization and bucket, and confirm with one controlled test write that shows up in a query against that bucket.

    Edge computing and IIoT

  • How-to

    Export InfluxDB CSV from ctrlX CORE Device Bridge data

    Post a bounded Flux query to the /api/v2/query endpoint with Accept: application/csv and a read token, or run an InfluxDB in node into csv and file nodes in Node-RED. Keep each request's row count small: rows equal series count times window length divided by sample interval.

    Edge computing and IIoT

  • Troubleshooting

    Why Node-RED on ctrlX COREvirtual cannot reach PostgreSQL

    The refusal comes from the destination, not from PostgreSQL: 127.0.0.1 inside ctrlX COREvirtual is the virtual controller itself, so Node-RED dials a guest loopback where nothing listens. From the QEMU guest the Windows host is always 10.0.2.2, so point node-red-contrib-re-postgres at 10.0.2.2:5432. A port-forwarding entry reads host port first, guest port second, and a boot failure naming a rule means that host port is already taken.

    Edge computing and IIoT

Why InfluxDB asynchronous writes never land in the bucket