Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a minimal c++ example in doc #516

Merged
merged 2 commits into from
Apr 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 81 additions & 3 deletions docs/cpp.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,86 @@
Users are typically migrating from [cc_image](https://github.com/bazelbuild/rules_docker#cc_image)
in rules_docker.

TODO: document how to build an image
## An example of packaging a simple C++ program

## Example
Using a minimal example C++ program `example.cc`:
```cpp
#include <iostream>

An example is needed! Please consider contributing one. :pray:
int main(){
std::cout<<"This is a C++ example!"<<std::endl;
}
```

To make a container image for this program, the `BUILD.bazel` would have something like this:
```python
load("@rules_oci//oci:defs.bzl", "oci_image", "oci_tarball")
load("@rules_cc//cc:defs.bzl", "cc_binary")
load("@rules_pkg//pkg:tar.bzl", "pkg_tar")

package(default_visibility = ["//visibility:public"])

# Normal cc_binary
cc_binary(
name = "example_binary",
srcs = [
"example.cc",
]
)

# Packaging the binary into tar, which is needed by oci_image rule
pkg_tar(
name = "tar",
srcs = [":example_binary"],
)

# Making image
# C++ programs usually need some fundamental libraries such as glibc, libstdc++, etc.
# Correspondigly, use language-specific distroless images.
# Here we use gcr.io/distroless/cc-debian12 image for this C++ program.
oci_image(
name = "image",
base = "@distroless_cc_debian12",
tars = [":tar"],
entrypoint = ["/example_binary"],
)

# Create tarball from oci image that can be run by container runtime.
# The image is designated using `repo_tags` attribute.
oci_tarball(
name = "image_tarball",
image = ":image",
repo_tags = ["example:latest"],
)
```

In `MODULE.bazel` file, be sure to add the following sections:
```python
# Pull needed base image
oci.pull(
name = "distroless_cc_debian12",
image = "gcr.io/distroless/cc-debian12",
platforms = [
"linux/amd64",
"linux/arm/v7",
"linux/arm64/v8",
],
tag = "latest",
)
# Expose the base image
use_repo(oci, "distroless_cc_debian12")
```
```python
# Import rules_pkg
bazel_dep(name = "rules_pkg", version = "0.10.1")
```

To make tarball, execute:
```bash
bazel run //:image_tarball
```

Then to run the program with runtime, e.g., Docker:
```bash
docker run --rm example:latest
```