Repository: docker/compose

Issue:
[BUG] escaping dollar using $$ does not work when braces follow
### Description

In the compose.yaml file, I was used to escaping $ with $$. However recently this seems to fail when braces follow.

### Steps To Reproduce

compose.yaml:

```yaml
services:
  foo:
    build:
      context: .
      args:
        foo: $${bar}
```

Dockerfile:
```Dockerfile
FROM debian
ARG foo
RUN echo foo is $foo
```

Executing
```bash
docker compose --progress=plain build
```

fails with
```
WARNING: The "bar" variable is not set. Defaulting to a blank string.
-.json:18,19-22: Unknown variable; There is no variable named "bar"., and 1 other diagnostic(s)
```


Please note that
* removing the braces succeeds
* using plain docker with  `docker build --build-arg 'foo=${bar}' --progress=plain .` succeeds



### Compose Version

```Text
Docker version 28.4.0, build d8eb465
```

### Docker Environment

```Text
Client: Docker Engine - Community
 Version:    28.4.0
 Context:    default
 Debug Mode: false
 Plugins:
  buildx: Docker Buildx (Docker Inc.)
    Version:  v0.29.0
    Path:     /usr/libexec/docker/cli-plugins/docker-buildx
  compose: Docker Compose (Docker Inc.)
    Version:  v2.39.4
    Path:     /usr/libexec/docker/cli-plugins/docker-compose

Server:
 Containers: 33
  Running: 3
  Paused: 0
  Stopped: 30
 Images: 336
 Server Version: 28.4.0
 Storage Driver: overlay2
  Backing Filesystem: btrfs
  Supports d_type: true
  Using metacopy: false
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: systemd
 Cgroup Version: 2
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local splunk syslog
 CDI spec directories:
  /etc/cdi
  /var/run/cdi
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: b98a3aace656320842a23f4a392a33f46af97866
 runc version: v1.3.0-0-g4ca628d1
 init version: de40ad0
 Security Options:
  apparmor
  seccomp
   Profile: builtin
  cgroupns
 Kernel Version: 6.14.0-29-generic
 Operating System: Ubuntu 25.04
 OSType: linux
 Architecture: x86_64
 CPUs: 12
 Total Memory: 28.87GiB
 Name: [obfuscated]
 ID: a1831f45-6602-43f9-8b48-7fa9ae79fbe8
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 HTTP Proxy: [obfuscated]
 HTTPS Proxy: [obfuscated]
 No Proxy: [obfuscated]
 Experimental: false
 Insecure Registries:
  ::1/128
  127.0.0.0/8
 Live Restore Enabled: false
```

### Anything else?

* It worked some weeks ago.
* Is it related to #12637?

Hints from issue comments:
@ndeloof: Build config is produced without $ being escaped, this cause bake to fail parsing the config as it tries to interpolate on it's own.
```
$ docker compose build --print
{
  "group": {
    "default": {
      "targets": [
        "foo"
      ]
    }
  },
  "target": {
    "foo": {
      "context": "/Users/nicolas/truc",
      "dockerfile": "/Users/nicolas/truc/Dockerfile",
      "args": {
        "foo": "${bar}"
      },
      "labels": {
        "com.docker.compose.project": "truc",
        "com.docker.compose.service": "foo",
        "com.docker.compose.version": "2.39.4"
      },
      "tags": [
        "truc-foo"
      ],
      "output": [
        "type=docker"
      ]
    }
  }
}

$ docker buildx bake -f bake.json
[+] Building 0.0s (1/1) FINISHED                                                                                              docker:desktop-linux
 => [internal] load local bake definitions                                                                                                    0.0s
 => => reading bake.json 523B / 523B                                                                                                          0.0s
bake.json:14
--------------------
  12 |           "dockerfile": "/Users/nicolas/truc/Dockerfile",
  13 |           "args": {
  14 | >>>         "foo": "${bar}"
  15 |           },
  16 |           "labels": {
--------------------
ERROR: bake.json:14,19-22: Unknown variable; There is no variable named "bar"., and 1 other diagnostic(s)
```

Solution patch:
diff --git a/pkg/compose/build_bake.go b/pkg/compose/build_bake.go
index 3f2d5feb..71735dcb 100644
--- a/pkg/compose/build_bake.go
+++ b/pkg/compose/build_bake.go
@@ -280,6 +280,9 @@ func (s *composeService) doBuildBake(ctx context.Context, project *types.Project
 		return nil, err
 	}
 
+	// escape all occurrences of '$' as we interpolated everything that has to
+	b = bytes.ReplaceAll(b, []byte("$"), []byte("$$"))
+
 	if options.Print {
 		_, err = fmt.Fprintln(s.stdout(), string(b))
 		return nil, err



Test patch:
diff --git a/pkg/e2e/build_test.go b/pkg/e2e/build_test.go
index e70cce4f..e0533261 100644
--- a/pkg/e2e/build_test.go
+++ b/pkg/e2e/build_test.go
@@ -645,3 +645,11 @@ func TestBuildTLS(t *testing.T) {
 	res := icmd.RunCmd(cmd)
 	res.Assert(t, icmd.Expected{Err: "Built"})
 }
+
+func TestBuildEscaped(t *testing.T) {
+	c := NewParallelCLI(t)
+	// ensure local test run does not reuse previously build image
+	c.RunDockerOrExitError(t, "rmi", "build-test-tags")
+	res := c.RunDockerComposeCmd(t, "--project-directory", "./fixtures/build-test/escaped", "build", "--no-cache")
+	res.Assert(t, icmd.Expected{Out: "foo is ${bar}"})
+}
diff --git a/pkg/e2e/fixtures/build-test/escaped/Dockerfile b/pkg/e2e/fixtures/build-test/escaped/Dockerfile
new file mode 100644
index 00000000..dd507f4f
--- /dev/null
+++ b/pkg/e2e/fixtures/build-test/escaped/Dockerfile
@@ -0,0 +1,17 @@
+#   Copyright 2020 Docker Compose CLI authors
+
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+
+#       http://www.apache.org/licenses/LICENSE-2.0
+
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+
+FROM alpine
+ARG foo
+RUN echo foo is $foo
diff --git a/pkg/e2e/fixtures/build-test/escaped/compose.yaml b/pkg/e2e/fixtures/build-test/escaped/compose.yaml
new file mode 100644
index 00000000..997af4e9
--- /dev/null
+++ b/pkg/e2e/fixtures/build-test/escaped/compose.yaml
@@ -0,0 +1,6 @@
+services:
+  foo:
+    build:
+      context: .
+      args:
+        foo: $${bar}