I understand my C++ application must be built for the OS of the container in which it will run. I see many examples, including Docker’s hello-world where a build environment is created within a container like this:
host$ docker run --rm -it -v $PWD:/build ubuntu:16.04
container# apt-get install build-essential
container# cd /build
container# gcc -o hello hello.c
My question is, if I have “hello” already built by a non-Docker Ubuntu 16 VM, or hello built by a “bare metal” server running Ubuntu 16, is that binary safe to install and run in a ubuntu:16.04 Docker image? Or is there a requirement to compile all my code within a Docker container? I have not seen documentation or examples that the former (building outside of Docker for same OS) is safe/supported.
I do understand that if my hello depends on shared libraries, etc, I must install those shared libraries into the target Docker image for my hello to run.
You should be able to use the same binaries. I usually compile my java code outside the docker container and put it in. If you have issues then it is likely a mismatch between your build environment and the docker container.
However, when I did Go development which required a Linux, whereas my main development environment is Windows I did my builds on the docker container. The ideal step was to compile and output to a volume that is mounted and then copy the output to another docker container. Though I got lazy when I did mine and just downloaded “Go” + dependencies, build then delete the compilers … you can see it in https://github.com/trajano/docker-volume-plugins/blob/master/cifs-volume-plugin/Dockerfile
That, a matching base operating system (“Linux”), and matching hardware architecture, are the only requirements. If you can provide the correct shared library environment the distribution (“Ubuntu”) doesn’t need to match, and a binary built in a Docker environment or a VM or bare metal shouldn’t be substantially different.
(Consider your proposed Dockerfile:
FROM ubuntu:16.04
RUN apt-get install build-essential
COPY hello.c .
RUN gcc -o hello hello.c
It’s highly likely the C toolchain and the like in build-essential came from a non-Docker build farm, but will work fine.)