I have a simple project that has a Cassandra database in a docker container. The database contains only one keyspace and a table. I want to save the container as an image after creating the keyspace and the table. So in the new docker image, it will contain both. The main idea behind this is to use this new image to create TestContainers during the testing of the functionalities of the application. Also, I won't need to every time generate the table since the new container will have it anyway, and in the test classes I can only focus on the actual functionality testing.
The project contains a student service that has CRUD operations to add, update, get, and delete student data. I created the first container using the following docker-compose file
docker-compose.yml
version: '3'
services:
cassandra:
image: cassandra:latest
container_name: test-container-student
ports:
- 9042:9042
volumes:
- C:/Users/{username}/Documents/backup/student:/var/lib/cassandra
Student class
public class Student
{
public Guid StudentId { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public int Age { get; set; }
}
Then I ran this Program.cs to generate the keyspace and the students table.
using Cassandra;
namespace TestProject;
class Program
{
static void Main(string[] args)
{
// Define the Cassandra cluster
var cluster = Cluster.Builder()
.AddContactPoint("127.0.0.1")
.Build();
// Create a session
var session = cluster.Connect();
// Create the keyspace if it doesn't exist
session.Execute(@"
CREATE KEYSPACE IF NOT EXISTS StudentDetails
WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': 1
}");
session.Execute(@"
CREATE TABLE IF NOT EXISTS StudentDetails.students (
student_id UUID PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INT
)");
}
}
After running the project it successfully creates the keyspace and table. And I saved the docker image using docker commit
. Then I generated a new docker container using this new docker image. But when checked the tables in the new container, I realized that the table I previously created, is not there. Is there any way that I can successfully save the image with the table? Thank you.
I had done the same thing for superset
and worked. Following are the steps I followed.
cassandra:latest
ID using sudo docker ps
sudo docker commit <docker-container-id-of-cassandra> new-cassandra
docker-compose.yml
file location sudo docker-compose down
docker-compose.yml
with new cassandra imageversion: '3'
services:
cassandra:
image: new-cassandra
container_name: new-container-student # <- change name here
ports:
- 9042:9042
volumes:
- C:/Users/{username}/Documents/backup/student:/var/lib/cassandra
sudo docker-compose up -d