Write Maintainable Integration Tests with Docker

Testcontainer is an open source community focused on making integration tests easier across many languages. Gianluca Arbezzano is a Docker Captain, SRE at Influx Data and the maintainer of the Golang implementation of Testcontainer that uses the Docker API to expose a test-friendly library that you can use in your test cases. 

Photo by Markus Spiske on Unsplash.

The popularity of microservices and the use of third-party services for non-business critical features has drastically increased the number of integrations that make up the modern application. These days, it is commonplace to use MySQL, Redis as a key value store, MongoDB, Postgress, and InfluxDB – and that is all just for the database – let alone the multiple services that make up other parts of the application.

All of these integration points require different layers of testing. Unit tests increase how fast you write code because you can mock all of your dependencies, set the expectation for your function and iterate until you get the desired transformation. But, we need more. We need to make sure that the integration with Redis, MongoDB or a microservice works as expected, not just that the mock works as we wrote it. Both are important but the difference is huge.

In this article, I will show you how to use testcontainer to write integration tests in Go with very low overhead. So, I am not telling you to stop writing unit tests, just to be clear!

Back in the day, when I was interested in becoming  a Java developer, I tried to write an integration between Zipkin, a popular open source tracer, and InfluxDB. I ultimately failed because I am not a Java developer, but I did understand how they wrote integration tests, and I became fascinated.

Getting Started: testcontainers-java

Zipkin provides a UI and an API to store and manipulate traces, it supports Cassandra, in-memory, ElasticSearch, MySQL and many more platforms as storage. In order to validate that all the storage systems work, they use a library called testcontainers-java that is a wrapper around the docker-api designed to be “test-friendly.”Here is the Quick Start example:

public class RedisBackedCacheIntTestStep0 {
private RedisBackedCache underTest;

@Before
public void setUp() {
// Assume that we have Redis running locally?
underTest = new RedisBackedCache(“localhost”, 6379);
}

@Test
public void testSimplePutAndGet() {
underTest.put(“test”, “example”);

String retrieved = underTest.get(“test”);
assertEquals(“example”, retrieved);
}
}

At the setUp you can create a container (redis in this case) and expose a port. From here, you can interact with a live redis instance.

Everytime you start a new container, there is a “sidecar” called ryuk that keeps your Docker environment clean by removing containers, volumes and networks after a certain amount of time. You can also remove them from inside the test.The below example comes from Zipkin. They are testing the ElasticSearch integration and as the example shows, you can programmatically configure your dependencies from inside the test case.

public class ElasticsearchStorageRule extends ExternalResource {
static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchStorageRule.class);
static final int ELASTICSEARCH_PORT = 9200; final String image; final String index;
GenericContainer container;
Closer closer = Closer.create();

public ElasticsearchStorageRule(String image, String index) {
this.image = image;
this.index = index;
}
@Override

protected void before() {
try {
LOGGER.info(“Starting docker image ” + image);
container =
new GenericContainer(image)
.withExposedPorts(ELASTICSEARCH_PORT)
.waitingFor(new HttpWaitStrategy().forPath(“/”));
container.start();
if (Boolean.valueOf(System.getenv(“ES_DEBUG”))) {
container.followOutput(new Slf4jLogConsumer(LoggerFactory.getLogger(image)));
}
System.out.println(“Starting docker image ” + image);
} catch (RuntimeException e) {
LOGGER.warn(“Couldn’t start docker image ” + image + “: ” + e.getMessage(), e);
}

That this happens programmatically is key because you do not need to rely on something external such as docker-compose to spin up your integration tests environment. By spinning it up from inside the test itself, you have a lot more control over the orchestration and provisioning, and the test is more stable. You can even check when a container is ready before you start a test.

Since I am not a Java developer, I ported the library (we are still working on all the features) in Golang and now it’s in the main testcontainers/testcontainers-go organization.

func TestNginxLatestReturn(t *testing.T) {
ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: “nginx”,
ExposedPorts: []string{“80/tcp”},
}
nginxC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Error(err)
}
defer nginxC.Terminate(ctx)
ip, err := nginxC.Host(ctx)
if err != nil {
t.Error(err)
}
port, err := nginxC.MappedPort(ctx, “80”)
if err != nil {
t.Error(err)
}
resp, err := http.Get(fmt.Sprintf(“http://%s:%s”, ip, port.Port()))
if resp.StatusCode != http.StatusOK {
t.Errorf(“Expected status code %d. Got %d.”, http.StatusOK, resp.StatusCode)
}
}

Creating the Test

This is what it looks like:

ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: “nginx”,
ExposedPorts: []string{“80/tcp”},
}
nginxC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Error(err)
}
defer nginxC.Terminate(ctx)

You create the nginx container and with the defer nginxC.Terminate(ctx) command, you are cleaning up the container when the test is over. Remember ryuk? it is not a mandatory command, but testcontainers-go uses it to remove the containers at some point.

Modules

The Java library has a feature called modules where you get pre-canned containers such as databases (mysql, postgress, cassandra, etc.) or applications like nginx.The go version is working on something similar but it is still an open pr.

If you’d like to build a microservice your application relies on from the upstream video, this is a great feature. Or if you would like to test how your application behaves from inside a container (probably more similar to where it will run in prod). This is how it works in Java:

@Rule
public GenericContainer dslContainer = new GenericContainer(
new ImageFromDockerfile()
.withFileFromString(“folder/someFile.txt”, “hello”)
.withFileFromClasspath(“test.txt”, “mappable-resource/test-resource.txt”)
.withFileFromClasspath(“Dockerfile”, “mappable-dockerfile/Dockerfile”))

What I’m working on now

Something that I am currently working on is a new canned container that uses kind to spin up Kubernetes clusters inside a container. If your applications use the Kubernetes API, you can test it in integration:

ctx := context.Background()
k := &KubeKindContainer{}
err := k.Start(ctx)
if err != nil {
t.Fatal(err.Error())
}
defer k.Terminate(ctx)
clientset, err := k.GetClientset()
if err != nil {
t.Fatal(err.Error())
}
ns, err := clientset.CoreV1().Namespaces().Get(“default”, metav1.GetOptions{})
if err != nil {
t.Fatal(err.Error())
}
if ns.GetName() != “default” {
t.Fatalf(“Expected default namespace got %s”, ns.GetName())

This feature is still a work in progress as you can see from PR67.

Calling All Coders

The Java version for testcontainers is the first one developed, it has a lot of features not ported to the Go version or to other libraries as well such as JavaScript, Rust, .Net.

My suggestion is to try the one written in your language and to contribute to it. 

In Go we don’t have a way to programmatically build images. I am thinking to embed buildkit or img in order to get a damonless builder that doesn’t depend on Docker. The great part about working with the Go version is that all the container related libraries are already in Go, so you can do a very good work of integration with them.

This is a great chance to become part of this community! If you are passionate about testing framework join us and send your pull requests, or come to hang out on Slack.

Try It Out

I hope you are as excited as me about the flavour and the power this library provides. Take a look at the testcontainers organization on GitHub to see if your language is covered and try it out! And, if your language is not covered, let’s write it! If you are a Go developer and you’d like to contribute, feel free to reach out to me @gianarb, or go check it out and open an issue or pull request!

Docker Captain @GianArb gives the low down on how to write maintainable integration tests with #DockerClick To Tweet
The post Write Maintainable Integration Tests with Docker appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Top 4 Tactics To Keep Node.js Rockin’ in Docker

This is a guest post from Docker Captain Bret Fisher, a long time DevOps sysadmin and speaker who teaches container skills with his popular Docker Mastery courses including Docker Mastery for Node.js, weekly YouTube Live shows, and consults to companies adopting Docker.

Foxy, my Docker Mastery mascot is a fan of Node and Docker

We’ve all got our favorite languages and frameworks, and Node.js is tops for me. I’ve run Node.js in Docker since the early days for mission-critical apps. I’m on a mission to educate everyone on how to get the most out of this framework and its tools like npm, Yarn, and nodemon with Docker.

There’s a ton of info out there on using Node.js with Docker, but so much of it is years out of date, and I’m here to help you optimize your setups for Node.js 10+ and Docker 18.09+. If you’d rather watch my DockerCon 2019 talk that covers these topics and more, check it out on YouTube.

Let’s go through 4 steps for making your Node.js containers sing! I’ll include some quick “Too Long; Didn’t Read” for those that need it.

Stick With Your Current Base Distro

TL;DR: If you’re migrating Node.js apps into containers, use the base image of the host OS you have in production today. After that, my favorite base image is the official node:slim editions rather than node:alpine, which is still good but usually more work to implement and comes with limitations.

One of the first questions anyone asks when putting a Node.js app in Docker, is “Which base image should I start my Node.js Dockerfile from?”

slim and alpine are quite smaller than the default image

There are multiple factors that weigh into this, but don’t make “image size” a top priority unless you’re dealing with IoT or embedded devices where every MB counts. In recent years the slim image has shrunk down in size to 150MB and works the best across the widest set of scenarios. Alpine is a very minimal container distribution, with the smallest node image at only 75MB. However, the level of effort to swap package managers (apt to apk), deal with edge cases, and work around security scanning limitations causes me hold off on recommending node:alpine for most use cases.

When adopting container tech, like anything, you want to do what you can to reduce the change rate. So many new tools and processes come along with containers. Choosing the base image your devs and ops are most used to has many unexpected benefits, so try to stick with it when it makes sense, even if this means making a custom image for CentOS, Ubuntu, etc.

Dealing With Node Modules

TL;DR: You don’t have to relocate node_modules in your containers as long as you follow a few rules for proper local development. A second option is to move mode_modules up a directory in your Dockerfile, configure your container properly, and it’ll provide the most flexible option, but may not work with every npm framework.

We’re all now used to a world where we don’t write all the code we run in an app, and that means dealing with app framework dependencies. One common question is how to deal with those code dependencies in containers when they are a subdirectory of our app. Local bind-mounts for development can affect your app differently if those dependencies were designed to run on your host OS and not the container OS.

The core of this issue for Node.js is that node_modules can contain binaries compiled for your host OS, and if it’s different then the container OS, you’ll get errors trying to run your app when you’re bind-mounting it from the host for development. Note that if you’re a pure Linux developer and you develop on Linux x64 for Linux x64, this bind-mount issue isn’t usually a concern.

For Node.js I offer you two approaches, which come with their own benefits and limitations:

Solution A: Keep It Simple

Don’t move node_modules. It will still sit in the default subdirectory of your app in the container, but this means that you have to prevent the node_modules created on your host from being used in the container during development.

This is my preferred method when doing pure-Docker development. It works great with a few rules you must follow for local development:

Develop only through the container. Why? Basically, you don’t want to mix up the node_modules on your host with the node_modules in the container. On macOS and Windows, Docker Desktop bind-mounts your code across the OS barrier, and this can cause problems with binaries you’ve installed with npm for the host OS, that can’t be run in the container OS.Run all your npm commands through docker-compose. This means your initial npm install for your project should now be docker-compose run <service name> npm install.

Solution B: Move Container Modules and Hide Host Modules

Relocate node_modules up the file path in the Dockerfile so you can develop Node.js in and out of the container, and the dependencies won’t clash which you switch between host-native development and Docker-based development.

Since Node.js is designed to run on multiple OS’s and architectures, you may not want to always develop in containers. If you want the flexibility to sometimes develop/run your Node.js app directly on the host, and then other times spin it up in a local container, then Solution B is your jam.

In this case you need a node_modules on host that is built for that OS, and a different node_modules in the container for Linux.

The basic lines you’ll need to move node_modules up the path

Rules for this solution include:

Move the node_modules up a directory in the container image. Node.js always looks for a node_modules as a subdirectory, but if it’s missing, it’ll walk up the directory path until it finds one. Example of doing that in a Dockerfile here. To prevent the host node_modules subdirectory from showing up in the container, use a workaround I call an “empty bind-mount” to prevent the host node_modules from ever being used in the container. In your compose YAML it would look like this.This works with most Node.js code, but some larger frameworks and projects seem to hard-code in the assumption that node_modules is a subdirectory, which will rule out this solution for you.

For both of these solutions, always remember to add node_modules to your .dockerignore file (same syntax as .gitignore) so you’ll never accidentally build your images with modules from the host. You always want your builds to run an npm install inside the image build.

Use The Node User, Go Least Privilege

All the official Node.js images have a Linux user added in the upstream image called node. This user is not used by default, which means your Node.js app will run as root in the container by default. This isn’t the worst thing, as it’s still isolated to that container, but you should enable in all your projects where you don’t need Node to run as root. Just add a new line in your Dockerfile: USER node

Here are some rules for using it:

Location in the Dockerfile matters. Add USER after apt/yum/apk commands, and usually before npm install commands.It doesn’t affect all commands, like COPY, which has its own syntax for controlling owner of files you copy in.You can always switch back to USER root if you need to. In more complex Dockerfiles this will be necessary, like my multi-stage example that includes running tests and security scans during optional stages.Permissions may get tricky during development because now you’ll be doing things in the container as a non-root user by default. The way to often get around this is to do things like npm install by telling Docker you want to run those one-off commands as root: docker-compose run -u root npm install

Don’t Use Process Managers In Production

TL;DR: Except for local development, don’t wrap your node startup commands with anything. Don’t use npm, nodemon, etc. Have your Dockerfile CMD be something like  [“node”, “file-to-start.js”] and you’ll have an easier time managing and replacing your containers.

Nodemon and other “file watchers” are necessary in development, but one big win for adopting Docker in your Node.js apps is that Docker takes over the job of what we used to use pm2, nodemon, forever, and systemd for on servers.

Docker, Swarm, and Kubernetes will do the job of running healthchecks and restarting or recreating your container if it fails. It’s also now the job of orchestrators to scale the number of replicas of our apps, which we used to use tools like pm2 and forever for. Remember, Node.js is still single-threaded in most cases, so even on a single server you’ll likely want to spin up multiple container replicas to take advantage of multiple CPU’s.

My example repo shows you how to using node directly in your Dockerfile, and then for local development, either build use a different image stage with docker build –target <stage name>, or override the CMD in your compose YAML.

Start Node Directly in Dockerfiles

TL;DR I also don’t recommend using npm to start your apps in your Dockerfile. Let me explain.

I recommend calling the node binary directly, largely due to the “PID 1 Problem” where you’ll find some confusion and misinformation online about how to deal with this in Node.js apps. To clear up confusion in the blogosphere, you don’t always need a “init” tool to sit between Docker and Node.js, and you should probably spend more time thinking about how your app stops gracefully.

Node.js accepts and forwards signals like SIGINT and SIGTERM from the OS, which is important for proper shutdown of your app. Node.js leaves it up to your app to decide how to handle those signals, which means if you don’t write code or use a module to handle them, your app won’t shut down gracefully. It’ll ignore those signals and then be killed by Docker or Kubernetes after a timeout period (Docker defaults to 10 seconds, Kubernetes to 30 seconds.) You’ll care a lot more about this once you have a production HTTP app that you have to ensure doesn’t just drop connections when you want to update your apps.

Using other apps to start Node.js for you, like npm for example, often break this signaling. npm won’t pass those signals to your app, so it’s best to leave it out of your Dockerfiles ENTRYPOINT and CMD. This also has the benefit of having one less binary running in the container. Another bonus is it allows you to see in the Dockerfile exactly what your app will do when your container is launched, rather then also having to check the package.json for the true startup command.

For those that know about init options like docker run –init or using tini in your Dockerfile, they are good backup options when you can’t change your app code, but it’s a much better solution to write code to handle proper signal handling for graceful shutdowns. Two examples are some boilerplate code I have here, and looking at modules like stoppable.

Is That All?

Nope. These are concerns that nearly every Node.js team deals with, and there’s lots of other considerations that go along with that. Topics like multi-stage builds, HTTP proxies, npm install performance, healthchecks, CVE scanning, container logging, testing during image builds, and microservice docker-compose setups are all common questions for my Node.js clients and students.

If you’re wanting more info on these topics, you can watch my DockerCon 2019 session video on this topic, or check my 8-hours of Docker for Node.js videos at https://www.bretfisher.com/node Thanks for reading. You can reach me on Twitter, get my weekly DevOps and Docker newsletter, subscribe to my weekly YouTube videos and Live Show, and check out my other Docker resources and courses.

Keep on Dockering!

Docker Captain @bretfisher dives into 4 Ways to Keep #nodejs Rockin in DockerClick To Tweet

The post Top 4 Tactics To Keep Node.js Rockin’ in Docker appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Accelerate Application Delivery with Application Templates in Docker Desktop Enterprise

The Application Templates interface.

Docker Enterprise 3.0, now generally available, includes several new features that make it simpler and faster for developers to build and deliver modern applications in the world of Docker containers and Kubernetes. One such feature is the new Application Templates interface that is included with Docker Desktop Enterprise.

Application Templates enable developers to build modern applications using a library of predefined and organization-approved application and service templates, without requiring prior knowledge of Docker commands. By providing re-usable “scaffolding” for developing modern container-based applications, Application Templates accelerate developer onboarding and improve productivity.

The Application Templates themselves include many of the discrete components required for developing a new application, including the Dockerfile, custom base images, common compose service YAML, and application parameters (external ports and upstream image versions). They can even include boilerplate code and code editor configs.

With Application Templates, development leads, application architects, and security and operations teams can customize and share application and service templates that align to corporate standards. As a developer, you know you’re starting from pre-approved templates that  eliminate time-consuming configuration steps and error-prone manual setup. Instead, you have the freedom to customize and experiment so you can focus on delivering innovative apps. 

Application Templates In Action: A Short Demo

The Easiest and Fastest Way to Containerize Apps

Even if you’ve never run a Docker container before, there is a new GUI-based Application Designer interface in Docker Desktop Enterprise that makes it simple to view and select Application Templates, run them on your machine, and start coding. There’s also a docker template CLI interface (currently available in Experimental mode only), which provides the same functionality if you prefer command line to a GUI.

Underneath the covers, Application Templates create a Docker Application, a new packaging format based on the Cloud Native Application Bundle specification. Docker Applications make it easy to bundle up all the container images, configuration, and parameters and share them on Docker Hub or Docker Trusted Registry. 

Docker Desktop Enterprise comes pre-loaded with a library of common templates based on Docker Hub official images, but you can also create and use templates customized to your own organization’s specifications.

After developers select their template and scaffold it locally, source code can be mounted in the local containers to speed the inner loop code and test cycles. The containers are running right on the developer’s machine so any changes to the code will be visible immediately in the running application. 

Docker Desktop Enterprise with Application Templates is generally available now! Contact Docker today to get started.

Accelerate Application Delivery with Application Templates in #Docker Desktop EnterpriseClick To Tweet

Interested in finding out more?

Learn more about Docker Desktop EnterpriseCheck out Docker Enterprise 3.0, the only end-to-end platform for building, sharing and running container-based applicationsWatch the full Docker Desktop Enterprise product demoGet the detailed documentation on Application Templates

The post Accelerate Application Delivery with Application Templates in Docker Desktop Enterprise appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Introducing the new Docker Technology Partner Program

We’re pleased to announce the launch of the Docker Technology Partner (DTP) program as a strong foundation for the ongoing collaboration with our ecosystem partners. Together through the new program, Docker and our partners will accelerate providing our enterprise customers with proven collaborative solutions. 

Our industry-leading container platform has proceeded to become central to continuous, high-velocity innovation for more than 750 enterprises around the world. As such, we recognized the need to enhance our partner program to make it easier for customers to identify key partners from the ecosystem that will provide them with the most value. The DTP program is designed to ensure that Docker customers across a variety of company sizes and industries have access to our massive ecosystem of partners and are able to integrate Docker containers with other chosen technologies.  This program provides clear insight into our formal partnerships, as well as the depth of joint product integration. 

Our partners also receive due recognition for their hard work in ensuring compatibility and support with Docker Enterprise. As always, we truly do appreciate the continued support of our partners, and are proud to showcase their accomplishments in integrating and validating with the Docker platform. 

Whether you’re an existing Docker customer, or just getting started with the platform, we encourage you to learn more about our partners and some of their offerings. These products provide invaluable tools for IT operators and developers to get the Docker platform and associated applications running in production easily. Docker Enterprise works on all major cloud providers and operating systems, and supports both Kubernetes and Swarm, giving you access to the broadest range of partner solutions.  Additionally, you’ll find applications from our ISV partners to either run in your Docker Enterprise environment, or utilize when building your own applications.

There are three levels in the DTP program:

Verified – Partners who have engaged with Docker directly, and are publishing products on Docker Hub under a Verified Publisher account.Professional – Partners who have Certified (tested & supported) their products with Docker EnterprisePremier – Deepest level of integration with Docker Enterprise, requiring Certified technology to undergo category specific technology review. 

Please take a look at our growing list of Verified partners on Docker Hub, as well as our Professional partners! We will begin to invite partners individually to participate in our first round up of Premier partners in the near future. 

Learn More: 

Review the DTP program guide, and apply today!Learn more about Docker partners or find one in our directory. Learn more about Docker Enterprise and get a free trial today

You can contact us with any questions.

Introducing the new #Docker Technology Partner (DTP) programClick To Tweet
The post Introducing the new Docker Technology Partner Program appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Announcing Docker Enterprise 3.0 General Availability

Today, we’re excited to announce the general availability of Docker Enterprise 3.0 – the only desktop-to-cloud enterprise container platform enabling organizations to build and share any application and securely run them anywhere – from hybrid cloud to the edge.

Docker Enterprise 3.0 Demo

Leading up to GA, more than 2,000 people participated in the Docker Enterprise 3.0 public beta program to try it for themselves. We gathered feedback from some of these beta participants to find out what excites them most about the latest iteration of Docker Enterprise. Here are 3 things that customers are excited about and the features that support them:

Simplifying Kubernetes

Kubernetes is a powerful orchestration technology but due to its inherent complexity, many enterprises (including Docker customers) have struggled to realize the full value of Kubernetes on their own. Much of Kubernetes’ perceived complexity stems from a lack of intuitive security and manageability configurations that most enterprises expect and require for production-grade software. We’re addressing this challenge with Docker Kubernetes Service (DKS) – a Certified Kubernetes distribution that is included with Docker Enterprise 3.0. It’s the only offering that integrates Kubernetes from the developer desktop to production servers, with ‘sensible secure defaults’ out-of-the-box.

“Increasing application development velocity and digital agility are a strategic imperative for companies in all sectors today. Developer experience is the killer app,” said RedMonk co-founder, James Governor. “Docker Kubernetes Service and Docker Application aim to package and simplify developer and operator experience, making modern container based workflows more accessible to developers and operators alike.”

You can learn more about Docker Kubernetes Service here.

Automating Deployment of Containers and Kubernetes

One of the most common requests we’ve heard from customers has been to make it easier to deploy and manage their container environments. That’s why we introduced new lifecycle automation tools for day 1 and day 2 operations, helping customers accelerate and expand the deployment of containers and Kubernetes on their choice of infrastructure. Using a simple set of CLI commands, operations teams can easily deploy, scale, backup and restore and upgrade their Docker Enterprise clusters across hybrid and multi-cloud deployment on AWS, Azure, or VMware.

You can learn more about lifecycle automation tools here.

Building Modern Applications 

With the ever-increasing emphasis on making things easier and faster for developers, it’s no surprise that Docker Desktop Enterprise and Docker Application created a lot of excitement amongst beta participants. Docker Desktop Enterprise is a new developer tool that decreases the “time-to-Docker” – accelerating developer onboarding and improving developer productivity. Docker Application, based on the CNAB standard, is a new application format that enables developers to bundle the many distributed resources that comprise a modern application into a single object that can be easily shared, installed and run anywhere. Docker Desktop Enterprise also allows users to quickly and easily create Docker Applications leveraging pre-defined Application Templates that support any language or framework.

“The Docker Enterprise platform and its approach to simplifying how containerized applications are built, shared and run allows us to fail fearlessly. We can test new services easily and quickly and if they work, we can immediately enhance the mortgage experience for our customers,” said Don Bauer, Lead DevOps Engineer, Citizens Bank. “Docker’s investment in new capabilities like Docker Application and simplified cluster management will further improve developer productivity and lifecycle automation for us so that we can continue to bring new, differentiated services to market faster.” 

You can learn more about Docker Applications here.

How to Get Started

Try Docker Enterprise 3.0 for YourselfLearn More about What’s New in Docker Enterprise 3.0Sign up for the upcoming webinar series: Drive High-Velocity Innovation with Docker Enterprise 3.0

Big News! Announcing #Docker Enterprise 3.0 General AvailabilityClick To Tweet
The post Announcing Docker Enterprise 3.0 General Availability appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Get Ready for the Tech Preview of Docker Desktop for WSL 2

Today at OSCON, Scott Hanselman, Kayla Cinnamon, and Yosef Durr of Microsoft demonstrated some of the new capabilities coming with Windows Subsystem for Linux (WSL) 2, including how it will be integrated with Docker Desktop. As part of this demonstration, we are excited to announce that users can now sign up for the end of July Docker Desktop Technical Preview of WSL 2. WSL 2 is the second generation of a compatibility layer for running Linux binary executables natively on Windows. Since it was announced at Microsoft Build, we have been working in partnership with Microsoft to deliver an improved Linux experience for Windows developers and invite everyone to sign up for the upcoming Technical Preview release.

Improving the Linux Experience on Windows

There are over half a million active users of Docker Desktop for Windows today and many of them are building Java and Node.js applications targeting Linux-based server environments. Leveraging WSL 2 will make the Docker developer experience more seamless no matter what operating system you’re running and what type of application you’re building. And the performance improvements will be immediately noticeable.

WSL 2 introduces a significant architectural change as it is a full Linux kernel built by Microsoft, allowing Linux containers to run natively without emulation. With the new WSL 2 Docker Desktop preview you will get access to Linux workspaces, removing the need to maintain both Linux and Windows build scripts. WSL 2 also supports dynamic memory and CPU allocation and an improved startup time down from 40 seconds to 2 seconds! 

Preview of Docker Desktop with WSL2

Thanks to our collaboration with Microsoft, we are already hard at work on getting this into your hands ahead of the WSL 2 full availability. We have written core functionalities to deploy an integration package, run the daemon and expose it to Windows processes, with support for bind mounts and port forwarding to simplify the experience.

For more details on the engineering work involved, read this engineering blog post.

The Tech Preview will be available shortly and we look forward to hearing your feedback.

Sign-up for the Docker Desktop for WSL 2 Tech Preview notification

Interested in trying out the #tech preview of Docker Desktop for WSL 2? Learn more in this blog post and sign up for the beta.Click To Tweet
The post Get Ready for the Tech Preview of Docker Desktop for WSL 2 appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Docker’s Contribution to Authentication for Windows Containers in Kubernetes

When Docker Enterprise added support for Windows containers running on Swarm with the release of Windows Server 2016, we had to tackle challenges that are less pervasive in pure Linux environments. Chief among these was Active Directory authentication for container-based services using Group Managed Service Accounts, or gMSAs. With nearly 3 years of experience deploying and running Windows container applications in production, Docker has solved for a number of complexities that come with managing gMSAs in a container-based world. We are pleased to have contributed that work to upstream Kubernetes.

Challenges with gMSA in Containerized Environments

Aside from being used for authentication across multiple instances, gMSAs solves for two additional problems: 

Containers cannot join the domain, and;When you start a container, you never really know which host in your cluster it’s going to run on. You might have three replicas running across hosts A, B, and C today and then tomorrow you have four replicas running across hosts Q, R, S, and T. 

One way to solve for this transience is to place the gMSA credential specifications for your service on each and every host where the containers for that service might run, and then repeat that for every Windows service you run in containers. It only takes a few combinations of servers and services to realize this solution just doesn’t scale. You could also place the credential specs inside the image itself, but then you have issues with flexibility if you later change the credspec the service uses.

Figure 1: Managing the matrix of container, credspecs, and hosts doesn’t scale

With Docker Enterprise 3.0 we created a new way to manage gMSA credspecs in Swarm environments. Rather than manually creating and copying credspecs to every potential host, you can instead create a service configuration:

docker config create credspec… 

which is a cluster-wide resource and can be used as a parameter when you create a Windows container service:

docker service create –credential-spec=”config://credspec”…

Swarm then automatically provides the credential spec to the appropriate container at runtime. Much like a secret, the config is only provided to containers that require it; and unlike a typical docker config, the cred spec is not mounted as a file in the system.

Figure 2: Swarm and Kubernetes orchestrators provide gMSA credspecs only when & where needed

Bringing gMSA credspecs to Kubernetes

Now that Kubernetes 1.14 has added support for Windows, the number of Windows container applications is likely to increase substantially and this same gMSA support will be important to anybody trying to run production Windows apps in their Kubernetes environment. The Docker team has been supporting this effort within the Kubernetes project with help from the SIG-Windows community. gMSA support is in the Alpha release phase in Kubernetes 1.14. 

gMSAs in Kubernetes work in a similar fashion to the config in Swarm: you create a credspec for the gMSA, use Kubernetes RBAC to control which pods can access the credspec, and then your pods can access the appropriate gMSA as needed. Again, this is still in Alpha right now so if you want to try it out you will have to enable the feature first.

We have additional work we are contributing upstream in addition to the gMSA work, like CSI support for Windows workloads, and we’ll share more about that in the weeks ahead as they reach alpha release stages. 

Learn more about #Docker’s contribution to authentication for Windows containers in @kubernetesioClick To Tweet

Call to Action 

If you’re attending OSCON check out the “Deploying Windows apps with Draft, Helm, and Kubernetes” session by Jessica Deen Test out the new gMSA config specs, coming soon in Docker Enterprise 3.0Review and contribute to the Kubernetes Windows gMSA SIG or other enhancement proposalsLearn more about Microsoft Group Managed Service Accounts

The post Docker’s Contribution to Authentication for Windows Containers in Kubernetes appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

10 Reasons Developers Love Docker

Developers ranked Docker as the #1 most wanted platform, #2 most loved platform, and #3 most broadly used platform in the 2019 Stack Overflow Developer Survey. Nearly 90,000 developers from around the world responded to the survey. So we asked the community why they love Docker, and here are 10 of the reasons they shared:
ROSIE the Robot at DockerCon. Her software runs on Docker containers.
 

It works on everyone’s machine. Docker eliminates the “but it worked on my laptop” problem.

“I love docker because it takes environment specific issues out of the equation – making the developer’s life easier and improving productivity by reducing time wasted debugging issues that ultimately don’t add value to the application.” @pamstr_

Takes the pain out of CI/CD. If there is one thing developers hate, it is doing the same thing over and over.

“Docker completely changed my life as a developer! I can spin up my project dependencies like databases for my application in a second in a clean state on any machine on our team! I can‘t not imagine the whole ci/cd-approach without docker. Automate all the stuff? Dockerize it!” @Dennis65560555 

Boosts your career. According to a recent Indeed report, in the last year, job postings listing Docker as a preferred skill have increased almost 50%. And the share of job searches per million including Docker has increased 9,538% since 2014.

Makes cool tech accessible. Whether you’re building your robot, experimenting with AI, or programming a Raspberry Pi, Docker makes it easy to work with interesting new technologies.

“I really find Docker an amazing piece of open platform which lets me to convert my Raspberry Pi’s into CCTV camera using Docker containers, pushing the live streaming data to Amazon Rekognition Service for Deep Learning & Facial Recognition using a single Docker Compose file.” @ajeetsraina (Docker Captain)

Raises productivity. It’s easier to ramp up quickly and there’s less busy-work with Docker.

“With containerized environments, my time from zero to contribution is almost non-existent. Same thing applies when switching to another project with completely different requirements. I can finally spend more time writing code and less time getting to the point of writing code. Oh! And I know it’ll work the same way in my build pipelines and prod!” @mikesir87 (Docker Captain)

Standardize Development + Deployments. Containers drive repeatability across processes, making it easier for both dev and ops, and ultimately driving business value. 

“Docker enables us to standardize our application deployment and development across On-Prem and Cloud platforms. We can now bring more value to our customers faster and standardized.” @idomyowntricks (Docker Captain)

Makes cloud migration easy. Docker runs on all the major cloud providers and operating systems, so apps containterized with Docker are portable across datacenters and clouds.

“Currently Docker is a key piece for migration to the cloud, for that reason is the most wanted and loved platform for the architects and developers ” @herrera_luis10 

Application upgrades are a lot easier. That’s true even for complex applications.

“I switched from Oracle 11g to 12c to 18c using Docker containers a few days ago. It worked absolutely painless on my Windows 10 workstation for testing purposes. I love working this way so much! Thanks Docker!” @dthater 

And, if an app breaks, it’s easy to fix. Rolling back to a known good state is simple with Docker.

“Love it because I broke my local PostgreSQL installation and decided that was the reason to switch to using a Docker compose file. Was up and running again in an hour, haven’t looked back” @J_Kreutzbender 

It’s easy to try out new apps. Testing new applications is much easier when you don’t have to build out infrastructure each time.

“I like @Docker because it allows for lightweight test drives of applications and services.” @burgwyn 
Docker Captain Don Bauer said it best:
“Docker has allows us to fail fearlessly. We can test new things easily and quickly and if they work, awesome. But if they don’t, we didn’t spend weeks or months on it. We might have spent a couple of hours or days.”

10 Reasons Why #Developers Love #DockerClick To Tweet

To find out more:

Get started with Docker Hub – a simple way for individual developers to start exploring Docker developer tools for common dev/test scenarios.
Learn more about Docker for Developers.
Read the Stack Overflow survey results.

The post 10 Reasons Developers Love Docker appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

Intro Guide to Dockerfile Best Practices

There are over one million Dockerfiles on GitHub today, but not all Dockerfiles are created equally. Efficiency is critical, and this blog series will cover five areas for Dockerfile best practices to help you write better Dockerfiles: incremental build time, image size, maintainability, security and repeatability. If you’re just beginning with Docker, this first blog post is for you! The next posts in the series will be more advanced.
Important note: the tips below follow the journey of ever-improving Dockerfiles for an example Java project based on Maven. The last Dockerfile is thus the recommended Dockerfile, while all intermediate ones are there only to illustrate specific best practices.
Incremental build time
In a development cycle, when building a Docker image, making code changes, then rebuilding, it is important to leverage caching. Caching helps to avoid running build steps again when they don’t need to.
Tip #1: Order matters for caching

However, the order of the build steps (Dockerfile instructions) matters, because when a step’s cache is invalidated by changing files or modifying lines in the Dockerfile, subsequent steps of their cache will break. Order your steps from least to most frequently changing steps to optimize caching.
Tip #2: More specific COPY to limit cache busts

Only copy what’s needed. If possible, avoid “COPY  .” When copying files into your image, make sure you are very specific about what you want to copy. Any changes to the files being copied will break the cache. In the example above, only the pre-built jar application is needed inside the image, so only copy that. That way unrelated file changes will not affect the cache.
Tip #3: Identify cacheable units such as apt-get update & install

Each RUN instruction can be seen as a cacheable unit of execution. Too many of them can be unnecessary, while chaining all commands into one RUN instruction can bust the cache easily, hurting the development cycle. When installing packages from package managers, you always want to update the index and install packages in the same RUN: they form together one cacheable unit. Otherwise you risk installing outdated packages.
Reduce Image size
Image size can be important because smaller images equal faster deployments and a smaller attack surface.
Tip #4: Remove unnecessary dependencies

Remove unnecessary dependencies and do not install debugging tools. If needed debugging tools can always be installed later. Certain package managers such as apt, automatically install packages that are recommended by the user-specified package, unnecessarily increasing the footprint. Apt has the –no-install-recommends flag which ensures that dependencies that were not actually needed are not installed. If they are needed, add them explicitly.
Tip #5: Remove package manager cache

Package managers maintain their own cache which may end up in the image. One way to deal with it is to remove the cache in the same RUN instruction that installed packages. Removing it in another RUN instruction would not reduce the image size.
There are further ways to reduce image size such as multi-stage builds which will be covered at the end of this blog post. The next set of best practices will look at how we can optimize for maintainability, security, and repeatability of the Dockerfile.
Maintainability
Tip #6: Use official images when possible

Official images can save a lot of time spent on maintenance because all the installation stamps are done and best practices are applied. If you have multiple projects, they can share those layers because they use exactly the same base image.
Tip #7: Use more specific tags

Do not use the latest tag. It has the convenience of always being available for official images on Docker Hub but there can be breaking changes over time. Depending on how far apart in time you rebuild the Dockerfile without cache, you may have failing builds.
Instead, use more specific tags for your base images. In this case, we’re using openjdk. There are a lot more tags available so check out the Docker Hub documentation for that image which lists all the existing variants.
Tip #8: Look for minimal flavors

Some of those tags have minimal flavors which means they are even smaller images. The slim variant is based on a stripped down Debian, while the alpine variant is based on the even smaller Alpine Linux distribution image. A notable difference is that debian still uses GNU libc while alpine uses musl libc which, although much smaller, may in some cases cause compatibility issues. In the case of openjdk, the jre flavor only contains the java runtime, not the sdk; this also drastically reduces the image size.
Reproducibility
So far the Dockerfiles above have assumed that your jar artifact was built on the host. This is not ideal because you lose the benefits of the consistent environment provided by containers. For instance if your Java application depends on specific libraries it may introduce unwelcome inconsistencies depending on which computer the application is built.
Tip #9: Build from source in a consistent environment
The source code is the source of truth from which you want to build a Docker image. The Dockerfile is simply the blueprint.

You should start by identifying all that’s needed to build your application. Our simple Java application requires Maven and the JDK, so let’s base our Dockerfile off of a specific minimal official maven image from Docker Hub, that includes the JDK. If you needed to install more dependencies, you could do so in a RUN step.
The pom.xml and src folders are copied in as they are needed for the final RUN step that produces the app.jar application with mvn package. (The -e flag is to show errors and -B to run in non-interactive aka “batch” mode).
We solved the inconsistent environment problem, but introduced another one: every time the code is changed, all the dependencies described in pom.xml are fetched. Hence the next tip.
Tip #10: Fetch dependencies in a separate step

By again thinking in terms of cacheable units of execution, we can decide that fetching dependencies is a separate cacheable unit that only needs to depend on changes to pom.xml and not the source code. The RUN step between the two COPY steps tells Maven to only fetch the dependencies.
There is one more problem that got introduced by building in consistent environments: our image is way bigger than before because it includes all the build-time dependencies that are not needed at runtime.
Tip #11: Use multi-stage builds to remove build dependencies (recommended Dockerfile)

Multi-stage builds are recognizable by the multiple FROM statements. Each FROM starts a new stage. They can be named with the AS keyword which we use to name our first stage “builder” to be referenced later. It will include all our build dependencies in a consistent environment.
The second stage is our final stage which will result in the final image. It will include the strict necessary for the runtime, in this case a minimal JRE (Java Runtime) based on Alpine. The intermediary builder stage will be cached but not present in the final image. In order to get build artifacts into our final image, use COPY –from=STAGE_NAME. In this case, STAGE_NAME is builder.

Multi-stage builds is the go-to solution to remove build-time dependencies.
We went from building bloated images inconsistently to building minimal images in a consistent environment while being cache-friendly. In the next blog post, we will dive more into other uses of multi-stage builds.

New blog from #Docker: Intro guide to Dockerfile best practicesClick To Tweet

Additional Resources:  

DockerCon Talk Recording: Dockerfile Best Practices
DockerCon Talk Slides: Dockerfile Best Practices
Docker Docs: Dockerfile References

The post Intro Guide to Dockerfile Best Practices appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/

A Secure Content Workflow from Docker Hub to DTR

Docker Hub is home to the world’s largest library of container images. Millions of individual developers rely on Docker Hub for official and certified container images provided by independent software vendors (ISV) and the countless contributions shared by community developers and open source projects. Large enterprises can benefit from the curated content in Docker Hub by building on top of previous innovations, but these organizations often require greater control over what images are used and where they ultimately live (typically behind a firewall in a data center or cloud-based infrastructure). For these companies, building a secure content engine between Docker Hub and Docker Trusted Registry (DTR) provides the best of both worlds – an automated way to access and “download” fresh, approved content to a trusted registry that they control.
Ultimately, the Hub-to-DTR workflow gives developers a fresh source of validated and secure content to support a diverse set of application stacks and infrastructures; all while staying compliant with corporate standards. Here is an example of how this is executed in Docker Enterprise 3.0:

Image Mirroring
DTR allows customers to set up a mirror to grab content from a Hub repository by constantly polling it and pulling new image tags as they are pushed. This ensures that fresh images are replicated across any number of registries in multiple clusters, putting the latest content right where it’s needed while avoiding network bottlenecks.
 

Access Controls
Advanced access controls let organizations to set permissions in DTR at a very granular level – down to the API. Images from Docker Hub can be mirrored into a restricted repository in DTR with access given only to qualified content administrators. The role of the content administrator is to ensure that the images meet the company’s policies.
Image Scanning
Once in the restricted repository, content administrators can set up automated vulnerability scanning which gives organization fine-grained visibility and control over the software and libraries that are being used. These binary-level scans compare the images and applications against the NIST CVE database to identify exposure to known security threats, providing organizations a chance to review and approve images before making them available to developers.
Policy-Based Image Promotion:
With DTR, content administrators can set up rules-based image promotion pipelines that automate the flow approved images to developer repository. (E.g. “Promote Image to Target if Vulnerability Scan shows Zero Major Vulnerabilities”.) This streamlines the development and delivery pipeline while enforcing security controls that automatically gate images, ensuring only approved content gets used by developers.

Image Signing
Digital signatures are used to verify both the contents and publisher of images, ensuring their integrity. Customers can also take this a step further by requiring signatures from specific users before images are deployed, providing an additional layer of trust. This allows content administrators to validate that they have approved images in the developer repositories. Developers and CI tools can apply signatures as well.
End-to-End Automation
The entire workflow outlined above can be automated within Docker Enterprise 3.0 – from image mirroring, to vulnerability scans that are triggered based on new content, to promotion policies and even the CI workflows that add digital signatures. This end-to-end automation enables enterprise developers to innovate on top of the vast content available in Docker Hub, while adhering to secure corporate standards and practices.

Learn how to combine @Docker Hub and Docker Trusted Registry with #Docker Enterprise 3.0 for a secure content workflowClick To Tweet

 
To learn more about Docker Enterprise 3.0:

Register for the Upcoming Docker Enterprise 3.0 Virtual Event
Try Docker Enterprise for yourself trial.docker.com 
Learn more about Docker Trusted Registry

The post A Secure Content Workflow from Docker Hub to DTR appeared first on Docker Blog.
Quelle: https://blog.docker.com/feed/